问题描述
我有一个原则上可以是任意长度的值表:
I have a table of values that can in principle be of any length:
Points =
{
"Point #1",
"Point #5",
"Point #7",
"Point #10",
"Point #5",
"Point #11",
"Point #5",
}
我想将它们作为参数传递给函数.
I want to pass them as arguments to a function.
addPath(<sPathName>, <sPoint>, <sPoint>, ...)
现在,通常您可以使用呼叫"功能.但在我使用的软件中,此功能不可用且不在范围内.
Now, normally you could use the "call" function. But in the software I am using this function is unavailable and not in scope.
如何在 Lua 4 中解决这个问题?
How do I get around this problem in Lua 4?
这里是我可以使用的功能.
推荐答案
在较新版本的 Lua 中,您将使用 unpack
,如 addPath(sPathName,unpack(Points))
,但 Lua 4.0 没有 unpack
.
In newer versions of Lua, you'd use unpack
, as in addPath(sPathName,unpack(Points))
, but Lua 4.0 does not have unpack
.
如果您可以添加 C 代码,Lua 5.0 中的 unpack
在 4.0 中可以正常工作:
If you can add C code, unpack
from Lua 5.0 works fine in 4.0:
static int luaB_unpack (lua_State *L) {
int n, i;
luaL_checktype(L, 1, LUA_TTABLE);
n = lua_getn(L, 1);
luaL_checkstack(L, n, "table too big to unpack");
for (i=1; i<=n; i++) /* push arg[1...n] */
lua_rawgeti(L, 1, i);
return n;
}
将此添加到 lbaselib.c
并将其添加到 base_funcs
:
Add this to lbaselib.c
and this to base_funcs
:
{"unpack", luaB_unpack},
如果您不能添加 C 代码,那么您就不走运了,可能会沦为这种黑客:
If you cannot add C code, then you're out of luck and are probably reduced to this hack:
function unpack(t)
return t[1],t[2],t[3],t[4],t[5],t[6],t[7],t[8],t[9],t[10]
end
根据需要扩展返回表达式,但最多只能扩展到 200 左右.让我们希望 addPath
忽略或停在第一个 nil
.
Extend the return expression as needed but you may only go as far as 200 or so. Let's hope that addPath
ignores or stops at the first nil
.
你也可以试试这个,它在第一个 nil 处停止,但没有明确的限制(有递归限制,它最多只能处理 250 个表条目):
You can also try this one, which stops at the first nil but has no explicit limits (there are recursion limits and it'll only handle up to 250 table entries):
function unpack(t,i)
i = i or 1
if t[i]~=nil then
return t[i],unpack(t,i+1)
end
end
这篇关于在 Lua 4 中将表值作为函数参数传递,无需“调用"功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!