From 9a5c447d0c06e0886fccd9a6f7487a587c5889d8 Mon Sep 17 00:00:00 2001 From: Kayne Ruse Date: Fri, 27 Mar 2015 20:42:36 +1100 Subject: [PATCH] userdata metatable is loaded smoothly --- server/server_logic.cpp | 12 +----------- server/userdata.cpp | 25 ++++++++++++++++++++++++- server/userdata.hpp | 4 +--- 3 files changed, 26 insertions(+), 15 deletions(-) diff --git a/server/server_logic.cpp b/server/server_logic.cpp index 57f7d2a..d2ae3d5 100644 --- a/server/server_logic.cpp +++ b/server/server_logic.cpp @@ -80,17 +80,7 @@ void ServerApplication::Init(int argc, char* argv[]) { std::cout << "Initialized lua" << std::endl; //create the userdata metatable - lua_pushlightuserdata(luaState, nullptr); //userdata - lua_createtable(luaState, 1, 0); //table - - //__index - lua_pushstring(luaState, "__index"); - lua_pushcfunction(luaState, userdataIndex); - lua_settable(luaState, -3); - - //set in the object - lua_setmetatable(luaState, -2); //set the metatable for userdata - lua_pop(luaState, 1); //pop the userdata + createUserdataMetatable(luaState); std::cout << "\tCreated userdata metatable" << std::endl; diff --git a/server/userdata.cpp b/server/userdata.cpp index 9e0bcb9..69d2e52 100644 --- a/server/userdata.cpp +++ b/server/userdata.cpp @@ -23,7 +23,30 @@ #include -int userdataIndex(lua_State* L) { +static int index(lua_State* L) { std::cout << "WARNING: userdataIndex called" << std::endl; + return 0; +} + +static luaL_Reg metatable[] = { + {"__index", index}, + {nullptr, nullptr} +}; + +int createUserdataMetatable(lua_State* L) { + //create the userdata metatable + lua_pushlightuserdata(L, nullptr); //anon userdata + lua_createtable(L, 0, 0); //table + + for (luaL_Reg* it = metatable; it->name; it++) { + lua_pushstring(L, it->name); + lua_pushcfunction(L, it->func); + lua_settable(L, -3); + } + + //set in the object & pop the anon userdata + lua_setmetatable(L, -2); //set the metatable for userdata + lua_pop(L, 1); //pop the anon userdata + return 0; } \ No newline at end of file diff --git a/server/userdata.hpp b/server/userdata.hpp index 98a6d87..b8c1622 100644 --- a/server/userdata.hpp +++ b/server/userdata.hpp @@ -24,8 +24,6 @@ #include "lua.hpp" -#define TORTUGA_USERDATA_NAME "userdata" - -int userdataIndex(lua_State* L); +int createUserdataMetatable(lua_State* L); #endif