tags:

views:

213

answers:

2

I am extending an interface with lua, and I've run into a problem in that I would need to pass pointers to objects to the lua code to work upon. These classes will have been wrapped via SWIG, and I could instantiate them via lua using swig, but that would leave me with useless objects.

I need to be able to pass a callback object to lua, as well as objects representing things on events. I cannot manually define the callback as global because that would introduce a constraint which is unnacceptable.

So for a generic example, given a class C and a function in lua that takes 1 parameter, how do I call that lua function while passing it the C++ pointer of type C?

A: 

I haven't used Swig with C++ and Lua, but you can do it without Swig in two different ways (userdata and closures). I don't know if Swig interferes somehow with this.

Using Userdata

lua_pushcclosure

Tuomas Pelkonen
+1  A: 

Aha, answering my own question, but I founds it!

http://lua-users.org/lists/lua-l/2007-05/msg00053.html

Hello Joey,

I do almost all my SWIG-LUA work from the lua side. Swig is really good for just wrappering up a C/C++ library to get it readable by lua. Getting the C++ to talk to lua is fairly easy, but not well documented.

You idea of lua_pushlightuserdata(), was close, but not there. You probably want something like this:

Foo* p= new Foo();
SWIG_NewPointerObj(L,p,SWIGTYPE_p_Foo,1);
lua_setglobal (L, "p");

The SWIG_NewPointerObj() creates a userdata (not a lightuserdata) for the foo object & pushes it to the stack. The last param (in this case 1) is whether you want lua to manage the memory (0 for no, 1 for yes).

The SWIG_NewPointerObj() and SWIGTYPE_p_Foo are both found in the wrapping file.

Once you have that you should be able to do in lua:

print(p)
print(swig_type(p))
p:some_function()

Let me know if you have any other questions. Regards, Mark

Tom J Nowell