lua-users home
lua-l archive

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


Am So., 20. Nov. 2022 um 07:16 Uhr schrieb bil til <biltil52@gmail.com>:
>
> PS: Sorry, this luaL_newmetatablex would need to defined as macro, I
> just recognized (my compiler gives warnings due to sizeof usage... the
> problem is, that lua_newlibtable is defined as macro with sizeof
> usage...), e. g. like this:
>
> #define luaL_newmetatablex (l, name, l__, l, nup)                         \


PPS: Sorry, one further correction, now I wrote my MyLuaL_addmeta
function like this, I want to post it here just to have it completed
somehow...:

  // see liolib.cpp
void MyLuaL_addmeta(lua_State *L, const char* pcName, const luaL_Reg
l__[], const luaL_Reg l[], int iElements) {
    // stack on input: lib table (call newlib)
    luaL_newmetatable(L, pcName); // metatable for file handles
    luaL_setfuncs(L, l__, 0);     // add metamethods to new metatable
    //luaL_newlibtable(L, l);  /* create method table */
    lua_createtable(L, 0, iElements-1);
    luaL_setfuncs(L, l, 0);  /* add file methods to method table */
    lua_setfield(L, -2, "__index");  /* metatable.__index = method table */
    lua_pop(L, 1);  /* pop metatable */
  }

... this looks quite final now, it is working very nicely. Typically,
there will be 3 function tables for a new lib, e. g. some
communication lib "com":
- the "lib functions" without colon notation (e. g. com.open):
     static const luaL_Reg comlib[] = {
       {cpcopen, com_open},
       {NULL, NULL}
   };

- the "lib meta functions" with colon notation (e. g. com:read,
com:write, com:close):
     static const luaL_Reg commeth[] = {
       {"read", com_read},
       {"write", com_write},
       {"close", com_close},
       {NULL, NULL}
     };

- the "lib meta internal functions", like __gc etc... .
     static const luaL_Reg metameth[] = {
       {"__index", NULL},  /* place holder */
       {"__gc", com_gc},
       {"__close", com_gc},
       {"__tostring", com_tostring},
       {NULL, NULL}
    };

And then the lib open function is very straight forward:

     #define elements(x) sizeof(x) / sizeof( (x)[0])
     LUAMOD_API int luaopen_com (lua_State *L) {
       luaL_newlib(L, comlib);  /* new module */
       MyLuaL_addmeta( L, "COM*", metameth, commeth, elements( commeth));
       return 1;
     }

... this really seems to work very perfect and nice now... .