Page 1 of 1
Using a single return value of a fucntion
Posted: Tue Jan 22, 2019 5:14 pm
by akopyl
How do I get the n-th return value of a function with multiple return values?
Here's something that doesn't work:
Code: Select all
function foo()
return 1, 2, 3
end
two = {foo()}[2]
Re: Using a single return value of a fucntion
Posted: Tue Jan 22, 2019 5:33 pm
by grump
Re: Using a single return value of a fucntion
Posted: Tue Jan 22, 2019 6:04 pm
by pgimeno
Note that select() returns all values starting on the specified one, so in this case it would return 2, 3. If you don't want that, you can isolate the parameter by wrapping the select in parentheses:
Code: Select all
local function foo()
return "a", "b", "c"
end
local table1 = { select(2, foo()) }
local table2 = { (select(2, foo())) }
print(#table1, #table2) -- prints 2, 1
Re: Using a single return value of a fucntion
Posted: Tue Jan 22, 2019 6:06 pm
by ivan
You cannot access the table on the same line as its definition:
Code: Select all
function foo()
return 1, 2, 3
end
res = {foo()}
two = res[2]
print (two)
Re: Using a single return value of a fucntion
Posted: Tue Jan 22, 2019 6:08 pm
by pgimeno
Oh you can, with parentheses:
But using that method implies creation and destruction of an object unnecessarily.
Re: Using a single return value of a fucntion
Posted: Tue Jan 22, 2019 6:26 pm
by akopyl
Thanks everyone! Very useful!
Re: Using a single return value of a fucntion
Posted: Tue Jan 22, 2019 10:26 pm
by monolifed