lua-users home
lua-l archive

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

>Is there anyway to register a C variable with Lua so that I can use it in c 
>and lua.  I am trying to do this:
>So that mouse can be changed and used in C and lua.

This has been discussed in the list before. See the postings with subject
	"Direct accessing of application variables from lua"
in the archive.  A solution is given in
	Message-Id: <>
but it's for Lua 3.x, so I'll repeat it below, updated for 4.0.
This is should be in the FAQ (which needs updating badly...)

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 (yes, tested!):

 static int I,J;

 static int getTint(lua_State* L)
  int* var=(int*) lua_touserdata(L,2);
  return 1;

 static int setTint(lua_State* L)
  int* var=(int*) lua_touserdata(L,2);
  int  val=(int)  lua_tonumber(L,3);
  return 0;

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

 /* test it! */
 int main(void)
  lua_State *L=lua_open(0);
  I=10; J=20;
  printf("(C) %d %d\n",I,J);
  lua_dostring(L,"I=100 J=200");
  printf("(C) %d %d\n",I,J);
  return 0;

I hope you get the idea.

lua_isuserdata before calling lua_touserdata 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 rawset 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