1

Good day, I would like to know how to convert table to ... and return it.

function GetArgsNormal(...)
    return ...;
end
local a,b,c=GetArgsNormal(1,2,3); --this works
print("a b c:",a,b,c);
function GetArgsTable(t,...)
    for i,v in pairs(t)do
        ({...})[i]=v;
    end
    return ...;
end
local d,e,f=GetArgsTable({1,2,3},nil); --result: d=nil, e=nil, f=nil
print("def:",d,e,f);

I tried all possible ways, which I had in my mind, but without success:(

Could anyone help me in this, please?

And yes, could you please answer instead of down-voting?!

4

2 回答 2

2
local d,e,f = unpack({1,2,3}); --result: d=1, e=2, f=3

function f()
   local t = {}
   -- fill table t
   return unpack(t)
end
于 2013-04-22T16:37:44.420 回答
1

您需要小心 args 中的“漏洞”

function GetArgsTable(t,...)
  local argc, argv = select("#", ...), {...}
  -- #argv ~= argc
  -- unpack(argv) ~= ...

  -- assume t is array
  for i,v in ipairs(t) do
    argc = argc + 1
    argv[argc] = v;
  end

  return unpack(argv, 1, argc); -- use explicit array size
end

print(GetArgsTable({1,2}, nil,'hello', nil)) -- nil hello nil 1 2

或者您可以查看 lua-vararg 库。

于 2013-04-28T07:02:12.090 回答