All the googling I've done so far has turned up things that are very close but just aren't quite cutting it for what I'm trying to do.
Let me describe this in the most basic way possible:
Imagine you have a C++ class
class A { public: int Method(); int Variable; };
Now imagine you instantiate A* Foo;
Now imagine you have a .lua file with this 3 line function:
function Test() local n = Foo:Method(); Foo.Variable = 0; local m = Foo.Variable; end
How can you bind the object A* to lua such that all those things are doable?
Pseudocode-wise, my first attempt went like this, partly from copy pasting examples:
When doing this, Foo:Hide(); successfully called my static function, which successfully unpacked the pointer and called its member Hide().
So far so good for :Method().
Then I tried to support the .Variable access. Everyone seemed to be saying to use metatables again this time overriding __index and __newindex and make them a sort of generic Get/Set, where you support certain keys as valid variable links eg if( key == "Variable" ) Variable = val;
This also worked fine.
The problem is trying to put those two things together. As soon as you override __index/__newindex with a getter/setter that works on Variable, the Method() call no longer calls the Method() static function, but goes into the __index function you bound instead.
All of that said, how does one support this seemingly basic combination of use cases?
Actual code snippets would be much more appreciated than purely theoretical chatter.
Reminder: please respond using the basic C API only, not third party stuff.
the Method() call no longer calls the Method() static function, but goes into the __index function you bound instead.
So program it so that if the key exists in the table, return that first, else go for getter/setter.
Use dedicated bindings such as luabridge or luabind
You'll end up writing faulty copies of those if you do it manually. Please provide a valid reason not to use ready binding libraries? Do you use STL in your C++ code?
you might also want to read lua-users:Binding Code to Lua
With LuaBridge:
#include <LuaBridge.h>
#include <RefCountedPtr.h>
...
struct A
{
int Method() { return 1; }
int Variable;
};
...
void register_my_stuff(lua_State *L) {
luabridge::getGlobalNamespace(L)
.beginClass<A>("A")
.addConstructor<void (*)(), RefCountedPtr<A> >()
.addFunction("Method", &A::Method)
.addData("Variable", &A::Variable)
.endClass()
;
}
Lua:
function Test()
local Foo = Core.A()
local n = Foo:Method()
assert ( n == 1 )
Foo.Variable = 42;
local m = Foo.Variable;
assert( m == 42 )
end
Test()
no need to write your own buggy boilerplate
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.