lua-users home
lua-l archive

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

>From: Falko Poiker <>

>> This is exactly what tolua does.
>Hmmm... That doesn't seem to be what I'm experiencing.  I have a large
>number of variables in my tolua.pkg file, and tolua creates a
>toluaI_set_<varname> and a toluaI_get_<varname> function for every one,

I'm sorry, you're right: tolua does that.

However, it can be done as I said before:
To export C variables to Lua as global variables, you need to create a tag
for each type, set get/setglobal tag methods for each tag, and define globals
in Lua whose values are userdata with the *address* of the C variables.

Something like this (tested!):

 extern int I,J;

 static void getTint(void)
  int* var=(int*) lua_getuserdata(lua_getparam(2));

 static void setTint(void)
  int* var=(int*) lua_getuserdata(lua_getparam(2));
  int val=(int) lua_getnumber(lua_getparam(3));

 void export(void)
  int Tint=lua_newtag();
  lua_pushusertag(&I,Tint);   lua_setglobal("I");
  lua_pushusertag(&J,Tint);   lua_setglobal("J");
  lua_pushcfunction(getTint); lua_settagmethod(Tint,"getglobal");
  lua_pushcfunction(setTint); lua_settagmethod(Tint,"setglobal");

I hope you get the idea.

In production code, you'll need some error checking, such as calling
lua_isuserdata before calling lua_getuserdata in getTint.
In this case, you might also print error messages such as "bad value for I",
using the name of global variable, which comes as the first argument to the
tag methods, but is ignored in the code above.

Alternatively, if you don't want to register C variables explicitly, and have
a list of the names (and addresses) of the variables you want to export,
then you might setup a get/setglobal tag method for tag(nil) and then check
whether the first argument in these tag methods is one of the names you
want to export; if it is, do the get/set; if not, return nil in the case of
get and call rawsetglobal in the case of set.

A cleaner solution would be to create a single global variable in Lua,
called "C" for clarity, and then talk with your C host via the "C" variable,
which woud contain a table and have appropriate get/settable tag methods.
So, in your Lua code, you could write

(perhaps "C" should be called "twk" instead, in this case).

I hope you get the idea. If there is demand, I can write a simple Lua program
that reads simple C declarations of variables to be exported and outputs
the necessary code; a sort of bare bones tolua.

I'll also talk with Waldemar about changing tolua to use this scheme instead of
creating 2 functions for each variable.