lua-users home
lua-l archive

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


It was thus said that the Great Henderson, Michael D once stated:
> 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

  You're close, but not quite there.  Changes indicated below.

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

  Add the following here:

  lua_pushvalue(L,-1);
  lua_setfield(L,-2,"__index");

This sets the __index field on the metatable, which will help.

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

  The line above needs to be:

  luaL_register(L,"mylib.core",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"?

  No need to worry about it as the metatable with the __index field will
take care of that for you.
   
>   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

  You already have it---it's in the variable ud.  

  -spc