Questions about the LÖVE API, installing LÖVE and other support related questions go here.
Forum rules
Before you make a thread asking for help,
read this .
akopyl
Prole
Posts: 21 Joined: Fri Jun 27, 2014 1:20 pm
Post
by akopyl » Tue Jan 22, 2019 5:14 pm
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]
grump
Party member
Posts: 947 Joined: Sat Jul 22, 2017 7:43 pm
Post
by grump » Tue Jan 22, 2019 5:33 pm
pgimeno
Party member
Posts: 3550 Joined: Sun Oct 18, 2015 2:58 pm
Post
by pgimeno » Tue Jan 22, 2019 6:04 pm
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
ivan
Party member
Posts: 1911 Joined: Fri Mar 07, 2008 1:39 pm
Contact:
Post
by ivan » Tue Jan 22, 2019 6:06 pm
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)
pgimeno
Party member
Posts: 3550 Joined: Sun Oct 18, 2015 2:58 pm
Post
by pgimeno » Tue Jan 22, 2019 6:08 pm
Oh you can, with parentheses:
But using that method implies creation and destruction of an object unnecessarily.
akopyl
Prole
Posts: 21 Joined: Fri Jun 27, 2014 1:20 pm
Post
by akopyl » Tue Jan 22, 2019 6:26 pm
Thanks everyone! Very useful!
Users browsing this forum: Ahrefs [Bot] , Google [Bot] , Semrush [Bot] and 81 guests