• Advertisement
Sign in to follow this  

C++ pointers in Lua

This topic is 3449 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

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

Share this post


Link to post
Share on other sites
Advertisement
You can't call methods on lightuserdata. If you use full userdata, you can define methods using metatables.

Share this post


Link to post
Share on other sites
Exactly, so the question is how do I tell Swig to generate metatables for Tile* as well as for Tile.

Share this post


Link to post
Share on other sites
Still no luck. There must be a way to register a pointer just the way an object itself is registered through metatable...

Share this post


Link to post
Share on other sites
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

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement