Using a single return value of a fucntion

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.
Post Reply
User avatar
akopyl
Prole
Posts: 21
Joined: Fri Jun 27, 2014 1:20 pm

Using a single return value of a fucntion

Post 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]
grump
Party member
Posts: 947
Joined: Sat Jul 22, 2017 7:43 pm

Re: Using a single return value of a fucntion

Post by grump »

Code: Select all

local two = select(2, foo())
User avatar
pgimeno
Party member
Posts: 3544
Joined: Sun Oct 18, 2015 2:58 pm

Re: Using a single return value of a fucntion

Post 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
User avatar
ivan
Party member
Posts: 1911
Joined: Fri Mar 07, 2008 1:39 pm
Contact:

Re: Using a single return value of a fucntion

Post 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)
User avatar
pgimeno
Party member
Posts: 3544
Joined: Sun Oct 18, 2015 2:58 pm

Re: Using a single return value of a fucntion

Post by pgimeno »

Oh you can, with parentheses:

Code: Select all

two = ({foo()})[2]
But using that method implies creation and destruction of an object unnecessarily.
User avatar
akopyl
Prole
Posts: 21
Joined: Fri Jun 27, 2014 1:20 pm

Re: Using a single return value of a fucntion

Post by akopyl »

Thanks everyone! Very useful!
monolifed
Party member
Posts: 188
Joined: Sat Feb 06, 2016 9:42 pm

Re: Using a single return value of a fucntion

Post by monolifed »

Code: Select all

_, two = foo()
Post Reply

Who is online

Users browsing this forum: Gopmyc and 45 guests