lua-users home
lua-l archive

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


On 11/10/06, Zé Pedro <zarroba@gmail.com> wrote:
Hi,
I have a similar problem, instead of a Vector a have a matrix of strings
that I have in C that I want to send to Lua for manipulation in there. I'm
aware that I can do it with metatables but I just don't know how. Imagine I
have the following function:
[snip]

I don't even bother with metatables.  I just convert C/C++ structures
and classes to nested tables.  I set up a function that looks
something like this and its inverse if I must get the table back into
the C/C++ struct/class.

// global
static SomeClass c;

// export this to Lua
static int class_to_lua_table(lua_State* L)
{
  lua_newtable(L);

  int table_stack_pos = lua_gettop(L);

  lua_pushnumber(L, c.val1);
  lua_setfield(L, table_stack_pos, "val1");

  lua_pushnumber(L, c.val2);
  lua_setfield(L, table_stack_pos, "val2");

  subclass_to_lua_table(L, c.sub);  // implementation implied
  lua_setfield(L, table_stack_pos, "sub");

  return 1;
}

Then, once you've registered that function to Lua, you can do this, for example.

c = class_to_lua_table()

print(c.val1, c.val2, c.sub.data1, c.sub.data2)

I find this to be the simplest solution but I basically just use C/C++
to bootstrap into Lua and implement all the logic in Lua so I either
don't need or can easily wrap the methods in the classes.  YMMV.

 Ken Smith