luaL_openlib 替代 Lua 5.2 [英] luaL_openlib replacement for Lua 5.2
问题描述
我正在改编一个为 Lua 编写的库 <5.2 接到一个电话,我不知道相当于:
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);
其中 polycoreLib
是一个
static const struct luaL_Reg polycoreLib []
如何替换对 luaL_openlib
的调用?
How can I replace the call to luaL_openlib
?
lua wiki 仅声明:
The lua wiki only states:
诸如luaL_openlib(L, name, lreg, x);
之类的调用应该仔细重写,因为将搜索并可能创建具有给定名称的全局表.
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.
推荐答案
对此有两个答案:一个用于复制早期版本的行为(在此处创建全局表),另一个用于实现现在的行为常规(即创建并返回一个匿名表).
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).
对于前者:
lua_newtable(L);
luaL_setfuncs(L, polycoreLib, 0);
lua_setglobal(L, "Polycore");
这与luaL_openlib
完全不一样,因为如果存在全局表Polycore
,它将覆盖它而不是合并用它.如果合并是一个问题,请先使用 lua_getglobal
,然后如果它推送了一个表,请重新使用它,而不是创建一个新的:
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"
这篇关于luaL_openlib 替代 Lua 5.2的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!