Reputation: 41
I want to pass a C++ object to Lua and use the same object in Lua. I have seen example of creating C++ objects in Lua and use them. But I want to do like this below.
I have gone through these examples here.
http://loadcode.blogspot.sg/2007/02/wrapping-c-classes-in-lua.html
https://gist.github.com/kizzx2/1594905
But they are creating C++ objects in Lua and using them in Lua scripts. can you please give some pointers.
Upvotes: 2
Views: 489
Reputation: 3000
Given that you did read some userdata manuals, it is very easy to achieve that. The only diference is that in regular ud manual they create objects in Lua function and you already have an object. Just push new userdata of pointer size and set it's metatable to Lua class's metatable (which you prepared anyway).
void **ud;
ud = lua_newuserdata(L, sizeof(*ud));
*ud = object; // existing
luaL_getmetatable(L, tname);
lua_setmetatable(L, -2);
// ud at top of stack
lua_setglobal(L, "foo");
Where tname is your Lua-side classes metatable name.
Upvotes: 2
Reputation: 14511
As you don't want to use the objects within Lua (just pass them on to C++), you can wrap them as a lightuserdata (see here) from C++, and later just pop it (you may want to check if it is_lightuserdata before).
Upvotes: 1