在不进行“调用"的情况下将表值作为函数参数传递给Lua 4.功能 [英] Passing table values as function arguments in Lua 4 without the "call" function
问题描述
我有一个原则上可以是任意长度的值表:
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
根据需要扩展return表达式,但是您最多只能输入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.功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!