Reputation:
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?!
Upvotes: 1
Views: 95
Reputation: 2235
You need to be careful with 'holes' in 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
Or you can look at lua-vararg library.
Upvotes: 1
Reputation: 23747
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
Upvotes: 2