lua-users home
lua-l archive

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


I'm upgrading to Lua 5.2.1 from 5.1.4 and am having difficulty finding examples on how one  defines 'classes' in 5.2 without using LUA_COMPAT_MODULE. I know I can use that to compile my code but it seems like the right thing to do is to move to the '5.2 way' since I'm going to the trouble of updating.

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) {
  luaL_newmetatable(L, test_class_name );
  lua_pushstring(L, "__index");
  lua_pushvalue(L, -2);
  lua_settable(L, -3);
  luaL_register(L, NULL, test_instance_methods);
  luaL_register(L, test_library_name, test_lib_methods);
  lua_pop(L, 2);
}

To create my object I use

static int test_new(lua_State *L) {
  test_t** test = (test_t**)lua_newuserdata(L,sizeof(test_t*));
  *test = new test_t();
  luaL_getmetatable(L, test_class_name);
  lua_setmetatable(L, -2);
  return 1;
}

And to pull my object out of the userdata I use

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");
  return *(test_t**)(ud);
}

If I don't define LUA_COMPAT_MODULE I can't use luaL_register. I've come up with the following that compiles and runs in straight in 5.2 but I'm not sure if it's the recommended way. I'm still using the same test_new and test_get functions.

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?