Let the top begin, that is, registering PersonManager in Lua. Since this is a singleton, we will register it as global.
void registerPersonManager(lua_State *lua) {
Now we are processing the PersonManager get method:
int lua_PersonManager_getPerson(lua_State *lua) { //Remember that first arbument should be userdata with your PersonManager //instance, as in Lua you would call PersonManager:getPerson("Stack Overflower"); //Normally I would first check, if first parameter is userdata with metatable //called PersonManagerMetaTable, for safety reasons PersonManager **pmPtr = (PersonManager**)luaL_checkudata( lua, 1, "PersonManagerMetaTable"); std::string personName = luaL_checkstring(lua, 2); Person *person = (*pmPtr)->getPerson(personName); if (person) registerPerson(lua, person); //Function that registers person. After //the function is called, the newly created instance of Person //object is on top of the stack else lua_pushnil(lua); return 1; } void registerPerson(lua_State *lua, Person *person) { //We assume that the person is a valid pointer Person **pptr = (Person**)lua_newuserdata(lua, sizeof(Person*)); *pptr = person; //Store the pointer in userdata. You must take care to ensure //the pointer is valid entire time Lua has access to it. if (luaL_newmetatable(lua, "PersonMetaTable")) //This is important. Since you //may invoke it many times, you should check, whether the table is newly //created or it already exists { //The table is newly created, so we register its functions lua_pushvalue(lua, -1); lua_setfield(lua, -2, "__index"); luaL_Reg personFunctions[] = { "getAge", lua_Person_getAge, nullptr, nullptr }; luaL_register(lua, 0, personFunctions); } lua_setmetatable(lua, -2); }
And finally, processing Person getAge .
int lua_Person_getAge(lua_State *lua) { Person **pptr = (Person**)lua_checkudata(lua, 1, "PersonMetaTable"); lua_pushnumber(lua, (*pptr)->getAge()); return 1; }
Now you should call registerPersonManager before executing the Lua code, best after creating a new Lua state and opening the necessary libraries.
Now in Lua you can do this:
local person = PersonManager:getPerson("Stack Overflower"); print(person:getAge());
At the moment, I don't have access to either Lua or C ++ to test it, but this should get you started. Please be careful with the lifetime of the Person pointer to which you provide Lua.