lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


> When I initialize my libraries ( which are usually both a static library along with a way to create an instance ) I use the following pattern
> 
> static void init(lua_State* L) {
>   [...]
>   lua_pushstring(L, "__index");
>   lua_pushvalue(L, -2);
>   lua_settable(L, -3);
--> you could use lua_setfield
>   [...]
> 
> static int test_new(lua_State *L) {
>   [...]
>   luaL_getmetatable(L, test_class_name);
>   lua_setmetatable(L, -2);
--> you could use luaL_setmetatable (as lhf pointed out)
> 
> static test_t* test_get(lua_State* L) {  
>   void *ud = luaL_checkudata(L, 1, test_class_name);
>   luaL_argcheck(L, ud != NULL, 1, "'Test Class' expected");
--> luaL_checkudata already does the check; It never returns NULL.


> static void init(lua_State* L) {
>   luaL_newmetatable(L, test_class_name );
>   lua_pushstring(L, "__index");
>   lua_pushvalue(L, -2);
>   lua_settable(L, -3);
>   luaL_setfuncs(L, test_methods, 0);
>   luaL_newlib(L, test_lib_methods);
>   lua_setglobal(L, "Test");
>   lua_pop(L, 2);
> }
> 
> Is there a more 5.2ish way of doing this sort of thing? 

Lua 5.2 does not recommend modules to create globals. Instead, the open
function should return the result from luaL_newlib and the library
should be used like this:

  local Test = require"Test"

-- Roberto