GreenHawk1220
GreenHawk1220

Reputation: 121

How do I store all results from a function into a single variable in Lua?

I have

function foo()
    return a, b
end
x, y = foo() -- x == a, y == b
z = foo() -- z == a

Is there a simpler way to transfer both a and b (and any more variable in the function) into z as an array?

initializing z with z = {} didn't work because it just redefines it as the first result of foo().

Upvotes: 2

Views: 766

Answers (1)

BJ Black
BJ Black

Reputation: 2531

How about:

-- define the function
function foo()
    return "one", "two"
end
-- set z to a table of the return values of foo().  The first return
-- value will be z[1], the second one z[2], and so on.
z = {foo()}
-- print it out
for k,v in pairs(z) do
    print(k, v)
end

Should get

1   one
2   two

Is that the sort of thing you're looking for?

Upvotes: 3

Related Questions