lua-users home
lua-l archive

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


I'm having trouble understanding how to work with classes and tables using the C API. By class I mean being able to use ":" to pass in a reference to self.

The questions are:
  // how do I add "init" to the table so that I can call "t:init"?

  // how do I get the table "self" that was passed in

  // how do I reference self.debug

They're copied in the example code below.


//--------- start module -----------

module(...)
local core = require 'mylib.core'

function init(p)
    local t = core.create({debug = false})
    t:init(p)
    return t
end

function foo(q)
    self.bah = q or false
end

//--------- end module -----------

//--------- start C API -----------

static const char *mtName = "mt.myLib";

int myCreate(lua_State *L);
int myInit(lua_State *L);

int luaopen_mylib_core(lua_State *L) {
  const struct luaL_Reg myLib[] = {
    {"create", myCreate},
    {"init"  , myInit},
    {0,0}
  }

  luaL_newmetatable(mtName);

  lua_createtable(L, 0, (sizeof(myLib)/sizeof(myLib[0]) + 3);
  lua_register(L, 0, myLib);

  lua_pushliteral(L, "compiled " __DATE__ " " __TIME__ "");
  lua_setfield(L, -2, "libDate");

  return 1;
}

int myCreate(lua_State *L) {
  MyStruct *ud = (MyStruct *)lua_newuserdata(L, sizeof(MyStruct));

  luaL_getmetatable(L, mtName);
  lua_setmetatable(L, -2);

  ud->ms = MyLibrary("parameters");

  // how do I add "init" to the table so that I can call "t:init"?

  return 1;
}

int myInit(lua_State *L) {
  // confirm that we're being passed a table that we created
  MyStruct *ud = (MyStruct *)luaL_checkudata(L, 1, mtName);

  // is "p" really the 2nd parameter?
  const char *p = luaL_checkstring(L, 2); 

  // how do I get the table "self" that was passed in

  // how do I reference self.debug

  return 1;
}

//--------- end C API -----------