I use lua as a scripting language for my 3d engine. I have lua "classes" for several objects and now I want to use properties instead of getters and setters. So instead of something like this
local oldState = ui:GetChild("Panel1"):GetVisible()
ui:GetChild("Panel1"):SetVisible(not oldState)
I would just
ui.Panel1.visible = not ui.Panel1.visible
The problem is my C++ code for creating metatables and instanced overrides the __index method. Here it is by the way:
Create a metatable:
void CLUAScript::RegisterClass(const luaL_Reg funcs[], std::string const& className) { luaL_newmetatable(m_lua_state, std::string("Classes." + className).c_str()); luaL_newlib( m_lua_state, funcs); lua_setglobal(m_lua_state, className.c_str()); }
Instantiate the class (the lua object only holds a pointer to an actual data that is stored in C++ code):
int CLUAScript::NewInstanceClass(void* instance, std::string const& className) { if (!instance) { lua_pushnil(m_lua_state); return 1; } luaL_checktype(m_lua_state, 1, LUA_TTABLE); lua_newtable(m_lua_state); lua_pushvalue(m_lua_state,1); lua_setmetatable(m_lua_state, -2); lua_pushvalue(m_lua_state,1); lua_setfield(m_lua_state, 1, "__index"); void **s = (void **)lua_newuserdata(m_lua_state, sizeof(void *)); *s = instance; luaL_getmetatable(m_lua_state, std::string("Classes." + className).c_str()); lua_setmetatable(m_lua_state, -2); lua_setfield(m_lua_state, -2, "__self"); return 1; }
The question is how can I have both methods and properties. If I just add __index
to CLUAScript::RegisterClass
funcs array it is never called. And I cannot imagine a way to remove its redefinition in CLUAScript::NewInstanceClass
.
If this code is not enough, here is the links to files working with lua: lua helper class, functions for UI, functions for Objects, and testing lua script
ui
and what doesui:GetChild("property_name")
return? For example, isui
an userdata from C++ land or is it some table returned byNewInstanceClass
with__self = udata_object
set? – greatwolfGetChild
andGetVisible
free standing functions in lua? Then you can just makeui.Panel1
as a form of syntax sugar that translates toGetChild(ui, "Panel1")
. – greatwolf