lua-users home
lua-l archive

passing pointers using LuaBridge

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


Hi all,
I am making moderate progress integrating Lua into my C++ environment. After trying many different ways of wrapping C or C++ code I ended up with two candidates that seemed to suit my needs best. LuaBridge (https://github.com/vinniefalco/LuaBridge) and LuaWrapper (https://bitbucket.org/alexames/luawrapper). I was able to create C++ wrappers for existing classes with both, and, inside my scripts, to create objects of those types and call methods upon them. So far so good. However, with both implementations I have failed to pass existing objects with C++ lifetime into the script.
With LuaBridge for example I do this (simplified):
int luaopen_mylib_1(lua_State *L) {
	using namespace luabridge;
	getGlobalNamespace(L)
		.beginNamespace("mylib")
			.addFunction ("testfree", testfree)
			.beginClass<MyClass>("MyClass")
				.addFunction("foo", &MyClass::foo )
			.endClass()
		.endNamespace();
	// quite like this interface btw.
	return 0;
}
... then ...
 using namespace luabridge;
 lua_State *L = luaL_newstate();
 luaL_openlibs(L);
 // and register the functions within that context
 luaopen_mylib_1(L);
 // create MyClass instance
 MyClass *p = new MyClass();
setGlobal(L, p, "mc"); // a LuaBridge Method that pushes the pointer as // global userdata on the stack
 if (luaL_dofile(L, "luawrapper_reuse.lua")) {
		std::cerr << "Lua program returned an error: \n";
		std::cerr << lua_tostring(L, -1);
		std::cerr << std::endl;
		lua_close(L);
 }
 delete p;
All very straight forward.
Then in my script...
[[
print("Executing LuaBridge test")
mylib.testfree()
mc:foo()
]]
The method testfree() is being called all right. At least I see the output. But then, when I try to access the instance "mc", I get:
luawrapper_reuse.lua:6: attempt to index global 'mc' (a userdata value)
Despite the fact that I do everything by the book, exactly the way it is described in LuaBridges manual. Can anyone tell me what I do wrong? How can I access the object? It seems like Lua does know it. A pointer by the name 'mc' has been pushed as userdata into the context, which is how I understand this is supposed to work. But why can I not de-reference it and call a method?
So close to the goal and yet all my efforts fail on this....
With that Test I use LuaJit 2.0 on Windows64 (MSVC9).
Help is much appreciated.
Thanks,
Moose.

AltStyle によって変換されたページ (->オリジナル) /