lua-users home
lua-l archive

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


Hi,

I once did a kind of linking of C variables to Lua, but I can't find the
code right now...

The C implementation was something along

float f;

static void l_getfloatvar()
{   void *ptr = lua_getusertag(lua_lua2C(2)); /* Err check omitted */

    lua_pushnumber(*(float*)ptr);
}

static void l_setfloatvar()
{   void *ptr = lua_getusertag(lua_lua2C(2)); /* Err check omitted */
    double x = lua_getnumber(lua_lua2C(3));

    *(float*)ptr = x;
}

void init_lua_cvars()
{ int tag_floatvar = lua_newtag();
  lua_pushcfunction(l_getfloatvar); lua_settagmethod(tag_floatvar,
"getglobal");
  lua_pushcfunction(l_setfloatvar); lua_settagmethod(tag_floatvar,
"setglobal");
  /*** similarly for other C types ***/

  lua_pushusertag(tag_float, &f); lua_setglobal("C_variable_f");
}

The value of the C variable f can then be queried and assigned using the
lua variable C_variable_f.
This obviously shouldn't be used for dynamic or automatic variables.

You might even call a function inside the tag methods to notify your
program of a Lua program getting or setting your variable in a way
similar to tcl's variable tracing facility; Unfortunately, you won't be
able to intercept a C function accessing the variable that easily.



-- 
Adolf Mathias              EMail: dolfi at zkm dot de  Web: www.zkm.de
|||| / |< ||| ZKM Institute for Visual Media - Institut für Bildmedien
P.B. 6919 D-76049 Karlsruhe, Germany; fon +49 721-8100-1544, fax -1509