Passing table values as function arguments in Lua 4 without the “call” function

余生颓废 提交于 2020-08-07 06:02:40

问题


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.

How do I get around this problem in Lua 4?

[edit]

Here are the functions I can use.


回答1:


In newer versions of Lua, you'd use unpack, as in addPath(sPathName,unpack(Points)), but Lua 4.0 does not have unpack.

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;
}

Add this to lbaselib.c and this to base_funcs:

  {"unpack", luaB_unpack},

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

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.

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


来源:https://stackoverflow.com/questions/19171723/passing-table-values-as-function-arguments-in-lua-4-without-the-call-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!