C++ pointers in Lua

Started by
4 comments, last by CmpDev 15 years, 5 months ago
Hey there, Given the following C++ classes class Tile { string GetName(); }; class Terrain { Tile* GetTile( int i, int j ); } I've generated a Swig wrapper for Tile and Terrain. Now I pass a Terrain object into the lua script: function doSomething( terrain ) tile = terrain:GetTile( 1, 2 ) tile:GetName() //runtime error ebd The first line works just fine, and tile now stores a pointer to a Tile object. The second line produces a runtime error "attempt to index global 'tile' (a userdata value)". I'm thinking this is the consequence of the fact that tile stores a pointer to Tile, not Tile itself. Obviously, there's no way I can dereference a C++ pointer inside Lua script. In my real situation I MUST return Tile* from Terrain::GetTile (and not Tile itself) since Tile is abstract and can only be returned as a pointer. When passing a pointer to Lua script I can overcome this problem by using Swig's SWIG_NewPointerObj, which allows me to do the stuff I want, so the following works fine: function func( pObj ) pObj:SomeMethod() end Where pObj is a pointer to some type So, the question is: is there any way to call a method on a pointer inside Lua script? Is there any workaround for the problem I've described? Thank you
Advertisement
You can't call methods on lightuserdata. If you use full userdata, you can define methods using metatables.
-- gekko
Exactly, so the question is how do I tell Swig to generate metatables for Tile* as well as for Tile.
Still no luck. There must be a way to register a pointer just the way an object itself is registered through metatable...
I'm sure there is, Luabind, Mluabind and toLua does support this functionality ( ie returning a ptr to a object from a bounded function and operating upon the ptr as if it was an instance within Lua). I've not looked at SWIG, so no idea how to configure it.

Try looking at how they do their implementation. IMO, Mluabind is the superior binding library of the 3.

Good Luck!

-ddn
Why not post your question to the Swig mailing list?

This topic is closed to new replies.

Advertisement