luaL_openlib替代Lua 5.2 [英] luaL_openlib replacement for Lua 5.2

查看:455
本文介绍了luaL_openlib替代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的呼叫?

仅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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆