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

前端 未结 1 580
温柔的废话
温柔的废话 2021-01-19 14:51

I have a table of values that can in principle be of any length:

Points =
{
    \"Point #1\",
    \"Point #5\",
    \"Point #7\",
    \"Point #10\",
    \"Po         


        
1条回答
  •  梦毁少年i
    2021-01-19 15:44

    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
    

    0 讨论(0)
提交回复
热议问题