lua-users home
lua-l archive

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


------------------------------
> 
> Message: 16
> Date: Fri, 15 Aug 2003 02:19:34 -0700 (PDT)
> From: Eric Wing <ewing2121@yahoo.com>
> Subject: Re: Looking for a better way with Lua, C++, and static
> 	members


Here is a technique I use:

struct foo
{
   static int set_i(lua_State* L);
   int i;
};

int foo::set_i(lua_State* L)
{
  foo* pFoo = reinterpret_cast<foo*>(lua_touserdata(L, lua_upvalue(1));
  pFoo->i = lua_tonumber(L, 1);
  return 0;
}

// Code to register the function and class instance with lua
foo f;

lua_State* L = lua_open();
lua_pushstring(L, "set_i");
lua_pushlightuserdata(L, &f);
lua_pushclosure(L, foo::set_i, 1);
lua_settable(L, LUA_GLOBALSINDEX);

lua_dofile(L, "foo.lua");

lua_close(L);

contents of foo.lua
-------------------
set_i(666);