author | Tero Marttila <terom@fixme.fi> |
Wed, 27 May 2009 23:57:48 +0300 | |
branch | new-lib-errors |
changeset 217 | 7728d6ec3abf |
parent 199 | 8eb839fbabba |
permissions | -rw-r--r-- |
143 | 1 |
#include "lua_type.h" |
2 |
||
3 |
#include <lua5.1/lauxlib.h> |
|
4 |
||
145 | 5 |
void lua_type_register (lua_State *L, const struct lua_type *type, const struct lua_method methods[]) |
143 | 6 |
{ |
145 | 7 |
const struct lua_method *method; |
8 |
||
9 |
// create the metatable |
|
10 |
luaL_newmetatable(L, type->name); |
|
143 | 11 |
|
12 |
// set the metatable __index to itself |
|
13 |
lua_pushvalue(L, -1); |
|
14 |
lua_setfield(L, -1, "__index"); |
|
15 |
||
145 | 16 |
// add the methods to the metatable |
146
24c0fc79d86a
fix bug with lua_type_register/methods
Tero Marttila <terom@fixme.fi>
parents:
145
diff
changeset
|
17 |
for (method = methods; method->func; method++) { |
145 | 18 |
lua_pushcfunction(L, method->func); |
19 |
lua_setfield(L, -2, method->name); |
|
20 |
} |
|
143 | 21 |
} |
22 |
||
145 | 23 |
void* lua_type_create (lua_State *L, const struct lua_type *type, size_t size) |
143 | 24 |
{ |
25 |
// create the new userdata on the stack |
|
26 |
void *ud = lua_newuserdata(L, size); |
|
27 |
||
28 |
// get the type and set it |
|
145 | 29 |
luaL_getmetatable(L, type->name); |
143 | 30 |
lua_setmetatable(L, -2); |
145 | 31 |
|
143 | 32 |
// ok |
33 |
return ud; |
|
34 |
} |
|
35 |
||
145 | 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) |
|
143 | 38 |
{ |
39 |
// allocate the global object |
|
40 |
void *obj = lua_newuserdata(L, size); |
|
41 |
||
42 |
// create the type metatable |
|
145 | 43 |
lua_type_register(L, type, methods); |
143 | 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 |
||
145 | 55 |
void* lua_type_get (lua_State *L, const struct lua_type *type, int index) |
143 | 56 |
{ |
57 |
void *ud; |
|
58 |
||
59 |
// validate the userdata arg |
|
199
8eb839fbabba
replace lua_client_networks/lua_network_channels with iterators
Tero Marttila <terom@fixme.fi>
parents:
146
diff
changeset
|
60 |
// XXX: the luaL_checkudata actually raises an error itself |
145 | 61 |
if ((ud = luaL_checkudata(L, index, type->name)) == NULL) { |
62 |
luaL_error(L, "bad type argument: `%s` expected", type->name); return NULL; |
|
143 | 63 |
|
64 |
} else { |
|
65 |
// ok |
|
66 |
return ud; |
|
67 |
||
68 |
} |
|
69 |
} |