2

say i have a function:

function func()
    return 1, 2, 3
end

Is there a way to elegantly reference individual return values? such as

if func() == 1 then
  print("stuff")
end

but instead reference the second or third returned value?

i realize you can do this

if ({func()})[2] == 2 then ...

but it just looks awful, and might as well just

_,v = func()
if v == 2 then ...

i'd like to do something like this

if func() == _,2 then ...

1 Answer 1

4

That would be select:

if select(2, func()) == 2 then ... end

print(select(1, func()) -- prints 1 2 3
print(select(2, func()) -- prints 2 3
print(select(3, func()) -- prints 3
print(select('#', func()) -- prints 3, the total number of arguments received
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.