luaL_openlib replacement for Lua 5.2

 ̄綄美尐妖づ 提交于 2019-11-29 05:45:12

问题


I am adapting a library written for Lua < 5.2 and got to a call I don't know the equivalent of:

luaL_openlib(L, "Polycore", polycoreLib, 0);

Where polycoreLib is a

static const struct luaL_Reg polycoreLib []

How can I replace the call to luaL_openlib?

The lua wiki only states:

Calls such as luaL_openlib(L, name, lreg, x); should be carefully rewritten because a global table with the given name will be searched and possibly created.


回答1:


There's two answers to this: one for replicating the behaviour of earlier versions here (where a global table is created), and one for implementing the behaviour that is now conventional (which is to create and return an anonymous table).

For the former:

lua_newtable(L);
luaL_setfuncs(L, polycoreLib, 0);
lua_setglobal(L, "Polycore");

This isn't quite the same as luaL_openlib, because if there is an existing global table Polycore it will overwrite it rather than merging with it. If merging is a concern, use lua_getglobal first, then if it pushed a table re-use that rather than creating a new one:

lua_getglobal(L, "Polycore");
if (lua_isnil(L, -1)) {
  lua_pop(L, 1);
  lua_newtable(L);
}
luaL_setfuncs(L, polycoreLib, 0);
lua_setglobal(L, "Polycore");

The latter is easier because you don't need to care about merging:

lua_newtable(L);
luaL_setfuncs(L, polycoreLib, 0);
return 1;

With this approach, it is the caller's reponsibility to bind the table, as in:

local Polycore = require "Polycore"


来源:https://stackoverflow.com/questions/19041215/lual-openlib-replacement-for-lua-5-2

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!