I'm still very new to Lua and I have a hard time trying to figure out the best approach when registering C functions in Lua, but from a C++ class, when it comes to retrieving the self pointer from an object that was not created from Lua.
Consider the following code:
foo.h
class Foo
{
public:
static int lua_DoSomething(lua_State* pState);
void DoSomething();
};
foo.cpp
static const luaL_Reg methods[] =
{
{"DoSomething", Foo::lua_DoSomething},
{nullptr, nullptr}
};
extern "C"
{
int luaopen_Foo(lua_State* pState)
{
luaL_register(pState, "Foo", methods);
return 1;
}
}
int Foo::lua_DoSomething(lua_State* pState)
{
Foo* self = ???; //<-- how to get self pointer here?
self->DoSomething();
return 0;
}
void Foo::DoSomething()
{
//...
}
script.lua
Foo.DoSomething();
So I got the function registered just fine and Foo::lua_DoSomething gets called (yay!).
However, since the Foo object is not created from Lua, how would I go to get the self pointer in function Foo::lua_DoSomething?
Do I have to register some kind of Foo::GetInstance function to Lua, to get the Foo pointer, and then use it in the Lua script somehow?
And what if there's multiple instance of Foo?
What's the cleanest general approach for objects not created from Lua?
Thanks!
Foo, or not. - DeduplicatorFoo* self = ???;will not compile, it was just to highlight the location where I needed help. Anyway, how would the Lua stack contain the pointer of my C++ object if the object wasn't created by Lua? - DeathiconFoobut you still need to get a hold of aFooinstance somehow. How is your lua-C binding API setup to do that currently? Milan's answer is likely the most helpful. - greatwolf