1 #include "lua_type.h" |
|
2 |
|
3 #include <lua5.1/lauxlib.h> |
|
4 |
|
5 void lua_type_register (lua_State *L, const struct lua_type *type, const struct lua_method methods[]) |
|
6 { |
|
7 const struct lua_method *method; |
|
8 |
|
9 // create the metatable |
|
10 luaL_newmetatable(L, type->name); |
|
11 |
|
12 // set the metatable __index to itself |
|
13 lua_pushvalue(L, -1); |
|
14 lua_setfield(L, -1, "__index"); |
|
15 |
|
16 // add the methods to the metatable |
|
17 for (method = methods; method->func; method++) { |
|
18 lua_pushcfunction(L, method->func); |
|
19 lua_setfield(L, -2, method->name); |
|
20 } |
|
21 } |
|
22 |
|
23 void* lua_type_create (lua_State *L, const struct lua_type *type, size_t size) |
|
24 { |
|
25 // create the new userdata on the stack |
|
26 void *ud = lua_newuserdata(L, size); |
|
27 |
|
28 // get the type and set it |
|
29 luaL_getmetatable(L, type->name); |
|
30 lua_setmetatable(L, -2); |
|
31 |
|
32 // ok |
|
33 return ud; |
|
34 } |
|
35 |
|
36 void* lua_type_register_global (lua_State *L, const struct lua_type *type, const struct lua_method methods[], |
|
37 const char *global_name, size_t size) |
|
38 { |
|
39 // allocate the global object |
|
40 void *obj = lua_newuserdata(L, size); |
|
41 |
|
42 // create the type metatable |
|
43 lua_type_register(L, type, methods); |
|
44 |
|
45 // set the userdata's metatable |
|
46 lua_setmetatable(L, -2); |
|
47 |
|
48 // store it as a global |
|
49 lua_setglobal(L, global_name); |
|
50 |
|
51 // ok |
|
52 return obj; |
|
53 } |
|
54 |
|
55 void* lua_type_get (lua_State *L, const struct lua_type *type, int index) |
|
56 { |
|
57 void *ud; |
|
58 |
|
59 // validate the userdata arg |
|
60 // XXX: the luaL_checkudata actually raises an error itself |
|
61 if ((ud = luaL_checkudata(L, index, type->name)) == NULL) { |
|
62 luaL_error(L, "bad type argument: `%s` expected", type->name); return NULL; |
|
63 |
|
64 } else { |
|
65 // ok |
|
66 return ud; |
|
67 |
|
68 } |
|
69 } |
|