lua-users home
lua-l archive

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


>From: Falko Poiker <fpoiker@relic.com>

>This brings up my next challenge - how do I pass pointers to structures and
>classes from my game to lua and back?  I'm assuming I use I use
>get/settable, however it's not clear to me how I keep track of the pointers
>using these tag methods.

>typedef struct Colour
>{
>	float r, g, b, a;  // I could also have methods in here to
>set/get/manipulate the data
>};
>
>Colour myColour;		// global within my application and lua
>
>in lua:
>
>myColour = {210, 0, 0, 0}
>myColour.a = 20

There are 2 issues here: get/setglobal and get/settable.

To be able to write
	myColour = {210, 0, 0, 0} 
in Lua, you need to set up a setglobal tag method for myColour.
This is done exactly as I showed before, creating a tag for the type Colour
and creating a global myColour in Lua whose value is a userdata of that tag,
using the address of myColour.
The difference is that in the setglobal tag method you'd get the fields of
a table and assign them to fields in the struct.
Something like this (untested)

 static void setTColour(void)
 {
  Colour* var=(Colour*) lua_getuserdata(lua_getparam(2));
  lua_Object val=lua_getparam(3);
  float f;
  lua_pushobject(val); lua_pushnumber(1); var->r=lua_getnumber(lua_gettable());
  lua_pushobject(val); lua_pushnumber(2); var->g=lua_getnumber(lua_gettable());
  lua_pushobject(val); lua_pushnumber(3); var->b=lua_getnumber(lua_gettable());
  lua_pushobject(val); lua_pushnumber(4); var->a=lua_getnumber(lua_gettable());
 }

Again, in production code, you'll need some error checking, and also
use lua_beginblock() and lua_endblock().

To be able to write
	myColour.a = 20
in Lua, you need to set up a settable tag method for myColour.
The code would be similar to the code above, except that would get the name
of the field too.

To get the value of myColour.a, you need to set up a gettable tag method.

I hope you get the idea.

You might also want to look at the output generated by tolua for your simple
example.
--lhf