Reputation: 1
I have a beginner question about using LuaPlus.
I'm looking at some code here inside an object constructor:
m_MetaTable = g_pApp->m_pLuaStateManager->GetGlobalState()->GetGlobals().CreateTable("EventManager");
m_MetaTable.SetObject("__index", m_MetaTable);
m_MetaTable.RegisterObjectDirect( "TriggerEvent", (EventManager *)0, &EventManager::TriggerEventFromScript );
m_MetaTable.RegisterObjectDirect( "RegisterEventType", (EventManager *)0, &EventManager::RegisterScriptEventType );
m_MetaTable.RegisterObjectDirect( "AddScriptListener", (EventManager *)0, &EventManager::AddScriptListener );
m_MetaTable.RegisterObjectDirect( "RemoveScriptListener", (EventManager *)0, &EventManager::RemoveScriptListener );
m_MetaTable.RegisterObjectDirect( "AddScriptActorListener", (EventManager *)0, &EventManager::AddScriptActorListener );
m_MetaTable.RegisterObjectDirect( "RemoveScriptActorListener", (EventManager *)0, &EventManager::RemoveScriptActorListener );
LuaPlus::LuaObject luaStateManObj = g_pApp->m_pLuaStateManager->GetGlobalState()->BoxPointer(this);
luaStateManObj.SetMetaTable(m_MetaTable);
g_pApp->m_pLuaStateManager->GetGlobalState()->GetGlobals().SetObject("EventManager", luaStateManObj);
First we create a metatable setting its __index equal to the metatable itself and associate some C++ functions with entries in the table. Now any table which uses this metatable should "inherit" these functions if I am understanding this correctly.
The part that I do not understand is the last 3 lines of code. It looks like we create a LuaObject and then associate it with the C++ object using this pointer, set its metatable to the same as above, and then create a global Lua variable so that it can be accessed in Lua script?
What is the point of doing this if any table which uses the above metatable already has access to the C++ member functions?
Upvotes: 0
Views: 616
Reputation: 185
I'm not sure what is the part that's confusing you, but here goes my understanding of each line
LuaPlus::LuaObject luaStateManObj = g_pApp->m_pLuaStateManager->GetGlobalState()->BoxPointer(this);
This line is creating a lua object that wraps a c++ pointer. This object exists in lua but in terms of the runtime, it's a nameless object so you can't access it from the lua side.
luaStateManObj.SetMetaTable(m_MetaTable);
Pretty self-explanatory, just set the metatable you created before to the object you just created.
g_pApp->m_pLuaStateManager->GetGlobalState()->GetGlobals().SetObject("EventManager", luaStateManObj);
Here you are giving the lua object you created a "lua name" so you can access it from the scripting side. After this line, if you execute a lua script calling an object named "EventManager" it will refer to the object you assigned here. Before this line, there's no object in lua bound to the "EventManager" name (assuming no one has defined it before).
Upvotes: 1