Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

source: orxonox.OLD/branches/script_engine/src/lib/script_engine/lunar.h @ 8157

Last change on this file since 8157 was 8101, checked in by bensch, 18 years ago

EXECUTOR USED

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