在Lua 4中,通过不使用“call”函数将表的值作为函数参数传递

我有一个可以拥有任意长度的值表:

Points =
{
    "Point #1",
    "Point #5",
    "Point #7",
    "Point #10",
    "Point #5",
    "Point #11",
    "Point #5",
}

我想将它们作为参数传递给一个函数。

addPath(<sPathName><sPoint><sPoint>,... )

现在,通常可以使用“call”函数。但在我使用的软件中,该函数不可用且不在范围内。

我该如何在Lua 4中解决这个问题?

[编辑]

这里是我可以使用的函数。

点赞
用户107090
用户107090

在新版本的 Lua 中,你可以使用 unpack,例如 addPath(sPathName,unpack(Points)),但是 Lua 4.0 不包含 unpack

如果你能够添加 C 代码,则在 Lua 4.0 中可以使用 Lua 5.0 中的 unpack

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 中:

  {"unpack", luaB_unpack},

如果您不能添加 C 代码,则只能使用以下方法:

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

您也可以尝试以下函数,它会在第一个 nil 处停止,但没有明确的限制(有递归限制,并且最多只能处理 250 个表项):

function unpack(t,i)
        i = i or 1
        if t[i]~=nil then
                return t[i],unpack(t,i+1)
        end
end
2013-10-04 01:47:36