Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

Changeset 8408 in orxonox.OLD for trunk/src/lib/script_engine


Ignore:
Timestamp:
Jun 14, 2006, 5:50:18 PM (18 years ago)
Author:
bensch
Message:

trunk: merged the script_engine branche back here
merged with command
svn merge https://svn.orxonox.net/orxonox/branches/script_engine . -r8284:HEAD
no conflicts

Location:
trunk/src/lib/script_engine
Files:
10 edited

Legend:

Unmodified
Added
Removed
  • trunk/src/lib/script_engine/Makefile.am

    r8271 r8408  
    1313
    1414libORXscript_a_SOURCES = \
    15                 script.cc\
    16                 script_manager.cc\
    17                 script_class.cc\
     15                script.cc \
     16                script_manager.cc \
     17                script_class.cc \
     18                script_method.cc \
     19                \
    1820                account.cc \
    1921                object.cc
     
    2527                lunar.h\
    2628                script.h\
    27                 script_manager.h\
    28                 script_class.h
     29                script_manager.h \
     30                script_class.h \
     31                script_method.h
    2932
    3033
     
    3235
    3336check_PROGRAMS = example
    34 
    35 
    36 
    37 
    38 
    39 
    40 
    4137example_DEPENDENCIES = \
    4238                $(MAINSRCDIR)/world_entities/libORXwe.a \
    4339                $(libORXlibs_a_LIBRARIES_) \
    4440                $(MAINSRCDIR)/util/libORXutils.a
    45 
    4641example_LDADD = \
    4742                $(MAINSRCDIR)/util/libORXutils.a \
  • trunk/src/lib/script_engine/account.cc

    r8271 r8408  
    1111
    1212
    13  class Account : public BaseObject {
    14       lua_Number m_balance;
    15    public:
    16      static const char className[];
    17      static Lunar<Account>::RegType methods[];
     13class Account : public BaseObject
     14{
     15  lua_Number m_balance;
     16public:
     17  Account(lua_State *L)      { m_balance = luaL_checknumber(L, 1); }
     18  Account(double balance=0)    : m_balance(balance) { this->setClassID(CL_ACCOUNT, "Account"); }
    1819
    19      Account(lua_State *L)      { m_balance = luaL_checknumber(L, 1); }
    20      Account(double balance=0)    : m_balance(balance) { this->setClassID(CL_ACCOUNT, "Account"); }
     20  void deposit (float value) { m_balance += value; };
     21  void withdraw(float value) { m_balance -= value; };
     22  float balance() { return m_balance; };
    2123
    22      void deposit (float value) { m_balance += value; };
    23      void withdraw(float value) { m_balance -= value; };
    24      float balance() { return m_balance; };
     24  int deposit (lua_State *L) { m_balance += luaL_checknumber(L, 1); return 0; }
     25  int withdraw(lua_State *L) { m_balance -= luaL_checknumber(L, 1); return 0; }
     26  int balance (lua_State *L) { lua_pushnumber(L, m_balance); return 1; }
     27  ~Account() { printf("deleted Account (%p)\n", this); }
     28};
    2529
    26      int deposit (lua_State *L) { m_balance += luaL_checknumber(L, 1); return 0; }
    27      int withdraw(lua_State *L) { m_balance -= luaL_checknumber(L, 1); return 0; }
    28      int balance (lua_State *L) { lua_pushnumber(L, m_balance); return 1; }
    29      ~Account() { printf("deleted Account (%p)\n", this); }
    30  };
    3130
    32  const char Account::className[] = "Account";
    3331
    34  Lunar<Account>::RegType Account::methods[] = {
    35    {"deposit", new ExecutorLua1<Account, float>(&Account::deposit)},
    36    {"withdraw", new ExecutorLua1<Account, float>(&Account::withdraw)},
    37    {"balance", new ExecutorLua0ret<Account, float>(&Account::balance)},
    38    {0,NULL}
    39  };
    40 
    41  CREATE_SCRIPTABLE_CLASS(Account, CL_ACCOUNT);
    42 
     32CREATE_SCRIPTABLE_CLASS(Account, CL_ACCOUNT,
     33                        addMethod("deposit", ExecutorLua1<Account, float>(&Account::deposit))
     34                        ->addMethod("withdraw", ExecutorLua1<Account, float>(&Account::withdraw))
     35                        ->addMethod("balance", ExecutorLua0ret<Account, float>(&Account::balance)));
  • trunk/src/lib/script_engine/lunar.h

    r8271 r8408  
    77
    88#include "luaincl.h"
    9 #include "executor/executor_lua.h"
    10 
    11 
    12 
    13     template <typename T> class Lunar {
    14       typedef struct { T *pT; } userdataType;
    15     public:
    16       typedef Executor* mfp;
    17       typedef struct { const char *name; mfp mfunc; } RegType;
    18 
    19 
    20       static void Register(Script* script)
     9#include "script_method.h"
     10
     11
     12
     13template <typename T> class Lunar
     14{
     15  typedef struct { T *pT; }
     16  userdataType;
     17public:
     18  typedef Executor* mfp;
     19  typedef struct { const char *name; mfp mfunc; }
     20  RegType;
     21
     22
     23  static void Register(Script* script, const std::string& className, const ScriptMethod* scriptMethods)
     24  {
     25    if(script != NULL)
     26      Register(script->getLuaState(), className, scriptMethods);
     27  }
     28
     29  static void Register(lua_State *L, const std::string& className, const ScriptMethod* scriptMethods)
     30  {
     31    Lunar<T>::className = className;
     32    Lunar<T>::scriptMethods = scriptMethods;
     33    lua_newtable(L);
     34    int methods = lua_gettop(L);
     35
     36    luaL_newmetatable(L, Lunar<T>::className.c_str());
     37    int metatable = lua_gettop(L);
     38
     39    // store method table in globals so that
     40    // scripts can add functions written in Lua.
     41    lua_pushvalue(L, methods);
     42    set(L, LUA_GLOBALSINDEX, Lunar<T>::className.c_str());
     43
     44    // hide metatable from Lua getmetatable()
     45    lua_pushvalue(L, methods);
     46    set(L, metatable, "__metatable");
     47
     48    lua_pushvalue(L, methods);
     49    set(L, metatable, "__index");
     50
     51    lua_pushcfunction(L, tostring_T);
     52    set(L, metatable, "__tostring");
     53
     54    lua_pushcfunction(L, gc_T);
     55    set(L, metatable, "__gc");
     56
     57    lua_newtable(L);                // mt for method table
     58    lua_pushcfunction(L, new_T);
     59    lua_pushvalue(L, -1);           // dup new_T function
     60    set(L, methods, "new");         // add new_T to method table
     61    set(L, -3, "__call");           // mt.__call = new_T
     62    lua_setmetatable(L, methods);
     63
     64    // fill method table with methods from class T
     65    /* as it was originally
     66    for (RegType *l = T::methods; l->name; l++)
     67    {
     68      lua_pushstring(L, l->name);
     69      lua_pushlightuserdata(L, (void*)l);
     70      lua_pushcclosure(L, thunk, 1);
     71      lua_settable(L, methods);
     72  }*/
     73    for (unsigned int i = 0; i < Lunar<T>::scriptMethods->size(); i++)
     74    {
     75      lua_pushstring(L, Lunar<T>::scriptMethods->name(i).c_str());
     76      lua_pushlightuserdata(L, (void*)Lunar<T>::scriptMethods->executor(i));
     77      lua_pushcclosure(L, thunk, 1);
     78      lua_settable(L, methods);
     79    }
     80    lua_pop(L, 2);  // drop metatable and method table
     81  }
     82
     83  // call named lua method from userdata method table
     84  static int call(lua_State *L, const char *method,
     85                  int nargs=0, int nresults=LUA_MULTRET, int errfunc=0)
     86  {
     87    int base = lua_gettop(L) - nargs;  // userdata index
     88    if (!luaL_checkudata(L, base, Lunar<T>::className.c_str()))
     89    {
     90      lua_settop(L, base-1);           // drop userdata and args
     91      lua_pushfstring(L, "not a valid %s userdata", Lunar<T>::className.c_str());
     92      return -1;
     93    }
     94
     95    lua_pushstring(L, method);         // method name
     96    lua_gettable(L, base);             // get method from userdata
     97    if (lua_isnil(L, -1))
     98    {            // no method?
     99      lua_settop(L, base-1);           // drop userdata and args
     100      lua_pushfstring(L, "%s missing method '%s'", Lunar<T>::className.c_str(), method);
     101      return -1;
     102    }
     103    lua_insert(L, base);               // put method under userdata, args
     104
     105    int status = lua_pcall(L, 1+nargs, nresults, errfunc);  // call method
     106    if (status)
     107    {
     108      const char *msg = lua_tostring(L, -1);
     109      if (msg == NULL) msg = "(error with no message)";
     110      lua_pushfstring(L, "%s:%s status = %d\n%s",
     111                      Lunar<T>::className.c_str(), method, status, msg);
     112      lua_remove(L, base);             // remove old message
     113      return -1;
     114    }
     115    return lua_gettop(L) - base + 1;   // number of results
     116  }
     117
     118  // push onto the Lua stack a userdata containing a pointer to T object
     119  static int push(lua_State *L, T *obj, bool gc=false)
     120  {
     121    if (!obj) { lua_pushnil(L); return 0; }
     122    luaL_getmetatable(L, Lunar<T>::className.c_str());  // lookup metatable in Lua registry
     123    if (lua_isnil(L, -1)) luaL_error(L, "%s missing metatable", Lunar<T>::className.c_str());
     124    int mt = lua_gettop(L);
     125    subtable(L, mt, "userdata", "v");
     126    userdataType *ud =
     127      static_cast<userdataType*>(pushuserdata(L, obj, sizeof(userdataType)));
     128    if (ud)
     129    {
     130      ud->pT = obj;  // store pointer to object in userdata
     131      lua_pushvalue(L, mt);
     132      lua_setmetatable(L, -2);
     133      if (gc == false)
    21134      {
    22         if(script != NULL)
    23           Register(script->getLuaState());
     135        lua_checkstack(L, 3);
     136        subtable(L, mt, "do not trash", "k");
     137        lua_pushvalue(L, -2);
     138        lua_pushboolean(L, 1);
     139        lua_settable(L, -3);
     140        lua_pop(L, 1);
    24141      }
    25 
    26       static void Register(lua_State *L) {
    27         lua_newtable(L);
    28         int methods = lua_gettop(L);
    29 
    30         luaL_newmetatable(L, T::className);
    31         int metatable = lua_gettop(L);
    32 
    33         // store method table in globals so that
    34         // scripts can add functions written in Lua.
    35         lua_pushvalue(L, methods);
    36         set(L, LUA_GLOBALSINDEX, T::className);
    37 
    38         // hide metatable from Lua getmetatable()
    39         lua_pushvalue(L, methods);
    40         set(L, metatable, "__metatable");
    41 
    42         lua_pushvalue(L, methods);
    43         set(L, metatable, "__index");
    44 
    45         lua_pushcfunction(L, tostring_T);
    46         set(L, metatable, "__tostring");
    47 
    48         lua_pushcfunction(L, gc_T);
    49         set(L, metatable, "__gc");
    50 
    51         lua_newtable(L);                // mt for method table
    52         lua_pushcfunction(L, new_T);
    53         lua_pushvalue(L, -1);           // dup new_T function
    54         set(L, methods, "new");         // add new_T to method table
    55         set(L, -3, "__call");           // mt.__call = new_T
    56         lua_setmetatable(L, methods);
    57 
    58         // fill method table with methods from class T
    59         for (RegType *l = T::methods; l->name; l++) {
    60           lua_pushstring(L, l->name);
    61           lua_pushlightuserdata(L, (void*)l);
    62           lua_pushcclosure(L, thunk, 1);
    63           lua_settable(L, methods);
    64         }
    65 
    66         lua_pop(L, 2);  // drop metatable and method table
    67       }
    68 
    69       // call named lua method from userdata method table
    70       static int call(lua_State *L, const char *method,
    71                       int nargs=0, int nresults=LUA_MULTRET, int errfunc=0)
    72       {
    73         int base = lua_gettop(L) - nargs;  // userdata index
    74         if (!luaL_checkudata(L, base, T::className)) {
    75           lua_settop(L, base-1);           // drop userdata and args
    76           lua_pushfstring(L, "not a valid %s userdata", T::className);
    77           return -1;
    78         }
    79 
    80         lua_pushstring(L, method);         // method name
    81         lua_gettable(L, base);             // get method from userdata
    82         if (lua_isnil(L, -1)) {            // no method?
    83           lua_settop(L, base-1);           // drop userdata and args
    84           lua_pushfstring(L, "%s missing method '%s'", T::className, method);
    85           return -1;
    86         }
    87         lua_insert(L, base);               // put method under userdata, args
    88 
    89         int status = lua_pcall(L, 1+nargs, nresults, errfunc);  // call method
    90         if (status) {
    91           const char *msg = lua_tostring(L, -1);
    92           if (msg == NULL) msg = "(error with no message)";
    93           lua_pushfstring(L, "%s:%s status = %d\n%s",
    94                           T::className, method, status, msg);
    95           lua_remove(L, base);             // remove old message
    96           return -1;
    97         }
    98         return lua_gettop(L) - base + 1;   // number of results
    99       }
    100 
    101       // push onto the Lua stack a userdata containing a pointer to T object
    102       static int push(lua_State *L, T *obj, bool gc=false) {
    103         if (!obj) { lua_pushnil(L); return 0; }
    104         luaL_getmetatable(L, T::className);  // lookup metatable in Lua registry
    105         if (lua_isnil(L, -1)) luaL_error(L, "%s missing metatable", T::className);
    106         int mt = lua_gettop(L);
    107         subtable(L, mt, "userdata", "v");
    108         userdataType *ud =
    109           static_cast<userdataType*>(pushuserdata(L, obj, sizeof(userdataType)));
    110         if (ud) {
    111           ud->pT = obj;  // store pointer to object in userdata
    112           lua_pushvalue(L, mt);
    113           lua_setmetatable(L, -2);
    114           if (gc == false) {
    115             lua_checkstack(L, 3);
    116             subtable(L, mt, "do not trash", "k");
    117             lua_pushvalue(L, -2);
    118             lua_pushboolean(L, 1);
    119             lua_settable(L, -3);
    120             lua_pop(L, 1);
    121           }
    122         }
    123         lua_replace(L, mt);
    124         lua_settop(L, mt);
    125         return mt;  // index of userdata containing pointer to T object
    126       }
    127 
    128 
    129       static int insertObject(lua_State* L, T* obj, const std::string& name, bool gc=false)
    130       {
    131         int objectRef = push(L, obj, gc);
    132 
    133         lua_pushlstring(L, name.c_str(), name.size());
    134         lua_pushvalue(L, objectRef );
    135         lua_settable(L, LUA_GLOBALSINDEX );
    136 
    137         return objectRef;
    138       }
    139 
    140 
    141       static int insertObject(Script* script, T* obj, const std::string& name, bool gc=false)
    142       {
    143         assert (script != NULL);
    144         return insertObject(script->getLuaState(), obj, name, gc);
    145       }
    146 
    147       // get userdata from Lua stack and return pointer to T object
    148       static T *check(lua_State *L, int narg) {
    149         userdataType *ud =
    150           static_cast<userdataType*>(luaL_checkudata(L, narg, T::className));
    151         if(!ud) luaL_typerror(L, narg, T::className);
    152         return ud->pT;  // pointer to T object
    153       }
    154 
    155     private:
    156       Lunar();  // hide default constructor
    157 
    158       // member function dispatcher
    159       static int thunk(lua_State *L) {
    160         // stack has userdata, followed by method args
    161         T *obj = check(L, 1);  // get 'self', or if you prefer, 'this'
    162         lua_remove(L, 1);  // remove self so member function args start at index 1
    163         // get member function from upvalue
    164         RegType *l = static_cast<RegType*>(lua_touserdata(L, lua_upvalueindex(1)));
    165         int value;
    166         (*l->mfunc)(obj, value, L);  // call member function
    167         return value;
    168       }
    169 
    170       // create a new T object and
    171       // push onto the Lua stack a userdata containing a pointer to T object
    172       static int new_T(lua_State *L) {
    173         lua_remove(L, 1);   // use classname:new(), instead of classname.new()
    174         T *obj = new T(L);  // call constructor for T objects
    175         push(L, obj, true); // gc_T will delete this object
    176         return 1;           // userdata containing pointer to T object
    177       }
    178 
    179       // garbage collection metamethod
    180       static int gc_T(lua_State *L) {
    181         if (luaL_getmetafield(L, 1, "do not trash")) {
    182           lua_pushvalue(L, 1);  // dup userdata
    183           lua_gettable(L, -2);
    184           if (!lua_isnil(L, -1)) return 0;  // do not delete object
    185         }
    186         userdataType *ud = static_cast<userdataType*>(lua_touserdata(L, 1));
    187         T *obj = ud->pT;
    188         if (obj) delete obj;  // call destructor for T objects
    189         return 0;
    190       }
    191 
    192       static int tostring_T (lua_State *L) {
    193         char buff[32];
    194         userdataType *ud = static_cast<userdataType*>(lua_touserdata(L, 1));
    195         T *obj = ud->pT;
    196         sprintf(buff, "%p", obj);
    197         lua_pushfstring(L, "%s (%s)", T::className, buff);
    198         return 1;
    199       }
    200 
    201       static void set(lua_State *L, int table_index, const char *key) {
    202         lua_pushstring(L, key);
    203         lua_insert(L, -2);  // swap value and key
    204         lua_settable(L, table_index);
    205       }
    206 
    207       static void weaktable(lua_State *L, const char *mode) {
    208         lua_newtable(L);
    209         lua_pushvalue(L, -1);  // table is its own metatable
    210         lua_setmetatable(L, -2);
    211         lua_pushliteral(L, "__mode");
    212         lua_pushstring(L, mode);
    213         lua_settable(L, -3);   // metatable.__mode = mode
    214       }
    215 
    216       static void subtable(lua_State *L, int tindex, const char *name, const char *mode) {
    217         lua_pushstring(L, name);
    218         lua_gettable(L, tindex);
    219         if (lua_isnil(L, -1)) {
    220           lua_pop(L, 1);
    221           lua_checkstack(L, 3);
    222           weaktable(L, mode);
    223           lua_pushstring(L, name);
    224           lua_pushvalue(L, -2);
    225           lua_settable(L, tindex);
    226         }
    227       }
    228 
    229       static void *pushuserdata(lua_State *L, void *key, size_t sz) {
    230         void *ud = 0;
    231         lua_pushlightuserdata(L, key);
    232         lua_gettable(L, -2);     // lookup[key]
    233         if (lua_isnil(L, -1)) {
    234           lua_pop(L, 1);         // drop nil
    235           lua_checkstack(L, 3);
    236           ud = lua_newuserdata(L, sz);  // create new userdata
    237           lua_pushlightuserdata(L, key);
    238           lua_pushvalue(L, -2);  // dup userdata
    239           lua_settable(L, -4);   // lookup[key] = userdata
    240         }
    241         return ud;
    242       }
    243     };
     142    }
     143    lua_replace(L, mt);
     144    lua_settop(L, mt);
     145    return mt;  // index of userdata containing pointer to T object
     146  }
     147
     148
     149  static int insertObject(lua_State* L, T* obj, const std::string& name, bool gc=false)
     150  {
     151    int objectRef = push(L, obj, gc);
     152
     153    lua_pushlstring(L, name.c_str(), name.size());
     154    lua_pushvalue(L, objectRef );
     155    lua_settable(L, LUA_GLOBALSINDEX );
     156
     157    return objectRef;
     158  }
     159
     160
     161  static int insertObject(Script* script, T* obj, const std::string& name, bool gc=false)
     162  {
     163    assert (script != NULL);
     164    return insertObject(script->getLuaState(), obj, name, gc);
     165  }
     166
     167  // get userdata from Lua stack and return pointer to T object
     168  static T *check(lua_State *L, int narg)
     169  {
     170    userdataType *ud =
     171      static_cast<userdataType*>(luaL_checkudata(L, narg, Lunar<T>::className.c_str()));
     172    if(!ud) luaL_typerror(L, narg, Lunar<T>::className.c_str());
     173    return ud->pT;  // pointer to T object
     174  }
     175
     176private:
     177  Lunar();  // hide default constructor
     178
     179  // member function dispatcher
     180  static int thunk(lua_State *L)
     181  {
     182    // stack has userdata, followed by method args
     183    T *obj = check(L, 1);  // get 'self', or if you prefer, 'this'
     184    lua_remove(L, 1);  // remove self so member function args start at index 1
     185    // get member function from upvalue
     186    Executor *l = static_cast<Executor*>(lua_touserdata(L, lua_upvalueindex(1)));
     187    int value;
     188    (*l)(obj, value, L);  // call member function
     189    return value;
     190  }
     191
     192  // create a new T object and
     193  // push onto the Lua stack a userdata containing a pointer to T object
     194  static int new_T(lua_State *L)
     195  {
     196    lua_remove(L, 1);   // use classname:new(), instead of classname.new()
     197    T *obj = new T();  // call constructor for T objects
     198    push(L, obj, true); // gc_T will delete this object
     199    return 1;           // userdata containing pointer to T object
     200  }
     201
     202  // garbage collection metamethod
     203  static int gc_T(lua_State *L)
     204  {
     205    if (luaL_getmetafield(L, 1, "do not trash"))
     206    {
     207      lua_pushvalue(L, 1);  // dup userdata
     208      lua_gettable(L, -2);
     209      if (!lua_isnil(L, -1)) return 0;  // do not delete object
     210    }
     211    userdataType *ud = static_cast<userdataType*>(lua_touserdata(L, 1));
     212    T *obj = ud->pT;
     213    if (obj) delete obj;  // call destructor for T objects
     214    return 0;
     215  }
     216
     217  static int tostring_T (lua_State *L)
     218  {
     219    char buff[32];
     220    userdataType *ud = static_cast<userdataType*>(lua_touserdata(L, 1));
     221    T *obj = ud->pT;
     222    sprintf(buff, "%p", obj);
     223    lua_pushfstring(L, "%s (%s)", Lunar<T>::className.c_str(), buff);
     224    return 1;
     225  }
     226
     227  static void set(lua_State *L, int table_index, const char *key)
     228  {
     229    lua_pushstring(L, key);
     230    lua_insert(L, -2);  // swap value and key
     231    lua_settable(L, table_index);
     232  }
     233
     234  static void weaktable(lua_State *L, const char *mode)
     235  {
     236    lua_newtable(L);
     237    lua_pushvalue(L, -1);  // table is its own metatable
     238    lua_setmetatable(L, -2);
     239    lua_pushliteral(L, "__mode");
     240    lua_pushstring(L, mode);
     241    lua_settable(L, -3);   // metatable.__mode = mode
     242  }
     243
     244  static void subtable(lua_State *L, int tindex, const char *name, const char *mode)
     245  {
     246    lua_pushstring(L, name);
     247    lua_gettable(L, tindex);
     248    if (lua_isnil(L, -1))
     249    {
     250      lua_pop(L, 1);
     251      lua_checkstack(L, 3);
     252      weaktable(L, mode);
     253      lua_pushstring(L, name);
     254      lua_pushvalue(L, -2);
     255      lua_settable(L, tindex);
     256    }
     257  }
     258
     259  static void *pushuserdata(lua_State *L, void *key, size_t sz)
     260  {
     261    void *ud = 0;
     262    lua_pushlightuserdata(L, key);
     263    lua_gettable(L, -2);     // lookup[key]
     264    if (lua_isnil(L, -1))
     265    {
     266      lua_pop(L, 1);         // drop nil
     267      lua_checkstack(L, 3);
     268      ud = lua_newuserdata(L, sz);  // create new userdata
     269      lua_pushlightuserdata(L, key);
     270      lua_pushvalue(L, -2);  // dup userdata
     271      lua_settable(L, -4);   // lookup[key] = userdata
     272    }
     273    return ud;
     274  }
     275
     276  private:
     277    static std::string className;
     278    static const ScriptMethod* scriptMethods;
     279};
     280
     281template <typename T>
     282    std::string Lunar<T>::className = "";
     283template <typename T>
     284    const ScriptMethod* Lunar<T>::scriptMethods = NULL;
    244285
    245286#endif /* _LUNAR_H */
  • trunk/src/lib/script_engine/lunartest2.lua

    r8271 r8408  
    2222
    2323function main(arg)
     24  io.write("hello i am main!")
    2425  -- use parameter
    2526  io.write("main received ", arg)
    2627  io.write(" as parameter\n")
    2728
     29 o = Object()
     30  o:printName()
    2831  --call member of an inserted object
    2932  Obj:printName()
    3033
    3134  --create object of a registered type
    32   o = Object()
    33   o:printName()
     35  --o = Object()
     36  --o:printName()
    3437
    3538  --take returnvalue from c
  • trunk/src/lib/script_engine/object.cc

    r8271 r8408  
    88
    99
    10 class Object : public BaseObject {
    11    public:
    12      static const char className[];
    13      static Lunar<Object>::RegType methods[];
     10class Object : public BaseObject
     11{
     12public:
     13  Object(lua_State* L) {callCount = 0; }
     14  Object(){callCount = 0;this->setClassID(CL_TEST_OBJECT, "Object");};
     15  ~Object() { printf("deleted Object (%p)\n", this); }
    1416
    15      Object(lua_State* L) {callCount = 0; }
    16      Object(){callCount = 0;};
    17      ~Object() { printf("deleted Object (%p)\n", this); }
     17  //meber functions
     18  void takeParam(int i)
     19  {
     20    printf("Lua passed %i to c++\n",i);
     21  }
    1822
    19         //meber functions
    20      void takeParam(int i)
    21      {
    22        printf("Lua passed %i to c++\n",i);
    23      }
     23  int printName(lua_State* L)
     24  {
     25    this->printName();
     26    return 0;
     27  }
    2428
    25      int printName(lua_State* L)
    26      {
    27        this->printName();
    28        return 0;
    29      }
     29  void printName()
     30  {
     31    callCount ++;
     32    printf("Hi i'm object %p ! This is the %i. call.\n",this,callCount);
     33  }
    3034
    31      void printName()
    32      {
    33        callCount ++;
    34        printf("Hi i'm object %p ! This is the %i. call.\n",this,callCount);
    35      }
     35  int getCallCount(){ return callCount; }
    3636
    37      int getCallCount(){ return callCount; }
     37private:
     38  int callCount;
    3839
    39    private:
    40      int callCount;
     40};
    4141
    42  };
    4342
    44  const char Object::className[] = "Object";
    45 
    46  Lunar<Object>::RegType Object::methods[] = {
    47    {"printName", new ExecutorLua0<Object>(&Object::printName)},
    48    {"getCallCount", new ExecutorLua0ret<Object, int>(&Object::getCallCount)},
    49    {"takeParam", new ExecutorLua1<Object, int>(&Object::takeParam)},
    50    {0,0}
    51  };
    52 
    53  CREATE_SCRIPTABLE_CLASS(Object, CL_TEST_OBJECT);
     43CREATE_SCRIPTABLE_CLASS(Object, CL_TEST_OBJECT,
     44                        addMethod("printName", ExecutorLua0<Object>(&Object::printName))
     45                        ->addMethod("getCallCount", ExecutorLua0ret<Object, int>(&Object::getCallCount))
     46                        ->addMethod("takeParam", ExecutorLua1<Object, int>(&Object::takeParam)));
  • trunk/src/lib/script_engine/script.cc

    r8271 r8408  
    2323  luaopen_math(luaState);
    2424  luaopen_debug(luaState);
    25 
    2625  if (root != NULL)
    2726    this->loadParams(root);
     
    3837void Script::loadParams(const TiXmlElement* root)
    3938{
     39  //printf("Loading params for %p \n",this);
    4040  BaseObject::loadParams(root);
    4141
     
    7777     else
    7878     {
    79       reportError(error);
    80      }
    81 
    82    }
    83    else
    84    {
     79       printf("ERROR while loading file %s: \n",filename.c_str());
     80       reportError(error);
     81     }
     82
     83   }
     84   else
     85   {
     86     printf("ERROR while loading file %s: \n",filename.c_str());
    8587     reportError(error);
    8688   }
     
    9294 void Script::addObject(const std::string& className, const std::string& objectName)
    9395 {
     96   //printf("Script %p: I am about to add %s of class %s\n",this,objectName.c_str(),className.c_str());
     97
    9498   BaseObject* scriptClass = ClassList::getObject(className, CL_SCRIPT_CLASS);
     99   //printf("The script class for %s is at %p \n",className.c_str(),scriptClass);
    95100   WorldObject tmpObj;
    96101   if (scriptClass != NULL)
     
    103108
    104109     BaseObject* object = ClassList::getObject(objectName, className);
     110     //printf("%s is at %p \n",objectName.c_str(),object);
    105111     if (object != NULL && !objectIsAdded(objectName))
    106112     {
     
    162168    if(error != 0)
    163169    {
     170     printf("ERROR while executing function %s: \n",currentFunction.c_str());
    164171     reportError(error);
     172     //clean up
     173     currentFunction.assign("");
     174     argumentCount = returnCount = 0;
    165175     return false;
    166176    }
     
    174184   else
    175185     printf("Error: no function selected.\n");
     186
     187   return false;
    176188 }
    177189
     
    229241 int Script::getReturnedInt()
    230242 {
    231    int returnValue;
     243   int returnValue = 0;
    232244   if(returnCount > 0)
    233245   {
    234      if(lua_isnumber(luaState, -1))
    235      {
    236        returnValue = (int)lua_tonumber(luaState, -1);
     246     if(lua_isnumber(luaState, -1*returnCount))
     247     {
     248       returnValue = (int)lua_tonumber(luaState, -1*returnCount);
     249       lua_remove(luaState,-1*returnCount);
    237250       returnCount--;
    238        lua_pop(luaState,1);
     251       
    239252     }
    240253   }
     
    245258 bool Script::getReturnedBool()
    246259 {
    247    bool returnValue;
     260   bool returnValue = false;
    248261   if(returnCount > 0)
    249262   {
    250      if(lua_isboolean(luaState, -1))
    251      {
    252        returnValue = (bool)lua_toboolean(luaState, -1);
     263     if(lua_isboolean(luaState, -1*returnCount))
     264     {
     265       returnValue = (bool)lua_toboolean(luaState, -1*returnCount);
     266       lua_remove(luaState,-1*returnCount);
    253267       returnCount--;
    254        lua_pop(luaState,1);
    255268     }
    256269   }
     
    260273float Script::getReturnedFloat()
    261274 {
    262    float returnValue;
     275   float returnValue = 0.0f;
    263276   if(returnCount > 0)
    264277   {
    265      if(lua_isnumber(luaState, -1))
    266      {
    267        returnValue = (float)lua_tonumber(luaState, -1);
     278     if(lua_isnumber(luaState, -1*returnCount))
     279     {
     280       returnValue = (float)lua_tonumber(luaState, -1*returnCount);
     281       lua_remove(luaState,-1*returnCount);
    268282       returnCount--;
    269        lua_pop(luaState,1);
    270283     }
    271284   }
     
    275288 void Script::getReturnedString(std::string& string)
    276289 {
    277    const char* returnValue;
     290   const char* returnValue = "";
    278291   if(returnCount > 0)
    279292   {
    280      if(lua_isstring(luaState, -1))
    281      {
    282        returnValue = lua_tostring(luaState, -1);
     293     if(lua_isstring(luaState, -1*returnCount))
     294     {
     295       returnValue = lua_tostring(luaState, -1*returnCount);
     296       lua_remove(luaState,-1*returnCount);
    283297       returnCount--;
    284        lua_pop(luaState,1);
    285298     }
    286299   }
     
    296309  fprintf(stderr, "ERROR: %s\n", msg);
    297310  lua_pop(luaState, 1);
     311 }
    298312  return error;
    299313 }
    300  }
    301314
    302315
  • trunk/src/lib/script_engine/script.h

    r8362 r8408  
    4747    bool executeFunction();
    4848
    49      // get returned values the last return value in lua is the first in c. TODO: change order of return
     49     // get returned values in the order the lua function returns it
    5050    int   getReturnedInt();
    5151    bool  getReturnedBool();
  • trunk/src/lib/script_engine/script_class.cc

    r8271 r8408  
    1717
    1818#include "script_class.h"
    19 
    20 using namespace std;
    21 
     19#include <cassert>
    2220
    2321/**
    24  * standard constructor
     22 * @brief standard constructor
    2523 * @todo this constructor is not jet implemented - do it
    2624*/
    27 ScriptClass::ScriptClass(const std::string& name, ClassID classID)
    28  : BaseObject(name)
     25ScriptClass::ScriptClass(const std::string& name, ClassID classID, ScriptMethod* scriptMethods)
     26    : BaseObject(name)
    2927{
    30    this->setClassID(CL_SCRIPT_CLASS, "ScriptClass");
    31    this->classID = classID;
     28  assert(scriptMethods != NULL);
     29  this->setClassID(CL_SCRIPT_CLASS, "ScriptClass");
     30
     31  this->_classID = classID;
     32
     33  this->_scriptMethods = scriptMethods;
    3234}
    3335
     
    3840ScriptClass::~ScriptClass ()
    3941{
    40   // delete what has to be deleted here
     42  delete this->_scriptMethods;
    4143}
  • trunk/src/lib/script_engine/script_class.h

    r8271 r8408  
    1111#include "script.h"
    1212#include "lunar.h"
    13 
    14 // FORWARD DECLARATION
     13#include "script_method.h"
    1514
    1615
     
    1918 * this should be used at the beginning of all the Classes that should be loadable (in the cc-file)
    2019 */
    21 #define CREATE_SCRIPTABLE_CLASS(CLASS_NAME, CLASS_ID) \
    22     tScriptable<CLASS_NAME> global_##CLASS_NAME##_ScriptableClass(#CLASS_NAME, CLASS_ID)
    23 
     20#define CREATE_SCRIPTABLE_CLASS(CLASS_NAME, CLASS_ID, SCRIPT_METHODS) \
     21    tScriptClass<CLASS_NAME> global_##CLASS_NAME##_ScriptableClass(#CLASS_NAME, CLASS_ID, (new ScriptMethod)->SCRIPT_METHODS)
    2422
    2523
     
    2826{
    2927
    30   public:
    31     virtual ~ScriptClass();
     28public:
     29  virtual ~ScriptClass();
    3230
    33     bool operator==(const std::string& name) { return (this->getName() == name); }
    34     bool operator==(ClassID classID) { return (this->classID == classID); }
     31  bool operator==(const std::string& name) { return (this->getName() == name); }
     32  bool operator==(ClassID classID) { return (this->_classID == classID); }
    3533
    36     virtual void registerClass(Script* script) = 0;
    37     virtual int insertObject(Script* L, BaseObject* obj, bool gc=false) = 0;
     34  virtual void registerClass(Script* script) = 0;
     35  virtual int insertObject(Script* L, BaseObject* obj, bool gc=false) = 0;
    3836
    39   protected:
    40     ScriptClass(const std::string& name, ClassID classID);
     37  const ScriptMethod* scriptMethods() const { return this->_scriptMethods; }
    4138
    42   private:
    43     ClassID             classID;
     39protected:
     40  ScriptClass(const std::string& name, ClassID classID, ScriptMethod* scriptMethods);
     41
     42private:
     43  ClassID             _classID;
     44  ScriptMethod*       _scriptMethods;
    4445};
    4546
     
    4849
    4950template <class T>
    50 class tScriptable : public ScriptClass
     51class tScriptClass : public ScriptClass
    5152{
    52   public:
    53     tScriptable(const std::string& name, ClassID classID)
    54         : ScriptClass(name, classID)
    55     { }
     53public:
     54  tScriptClass(const std::string& name, ClassID classID, ScriptMethod* scriptMethods)
     55      : ScriptClass(name, classID, scriptMethods)
     56  { }
    5657
    57     virtual void registerClass(Script* script)
    58     {
    59       Lunar<T>::Register(script);
    60     }
    61     virtual int insertObject(Script* L, BaseObject* obj, bool gc=false)
    62     {
    63       Lunar<T>::insertObject(L, dynamic_cast<T*>(obj), obj->getName(), gc);
    64     }
    65 
    66 
    67 
    68 }
    69 ;
     58  virtual void registerClass(Script* script)
     59  {
     60    Lunar<T>::Register(script, this->getName(), this->scriptMethods());
     61  }
     62  virtual int insertObject(Script* L, BaseObject* obj, bool gc=false)
     63  {
     64    return Lunar<T>::insertObject(L, dynamic_cast<T*>(obj), obj->getName(), gc);
     65  }
     66};
    7067
    7168
  • trunk/src/lib/script_engine/script_manager.cc

    r8278 r8408  
    11#include <string>
    22#include <list>
     3
     4#define DEBUG_SPECIAL_MODULE DEBUG_MODULE_WORLD
    35
    46
     
    1921{
    2022  this->setName("ScriptManager");
    21   printf("ScriptManager created\n");
    2223  this->scripts = NULL;
    2324  this->triggers = NULL;
     
    3738void ScriptManager::loadParams(const TiXmlElement* root)
    3839{
    39   //BaseObject::loadParams(root);
     40  BaseObject::loadParams(root);
    4041  {
    4142    LoadParamXML(root, "Scripts", this, ScriptManager, createScripts);
Note: See TracChangeset for help on using the changeset viewer.