Antony Thomas
Antony Thomas

Reputation: 3686

Multiple return values in Lua

Ran into this problem earlier. For a multi return value function

fn=function() return 'a','b' end

the call

print(fn()) returns a b

but the call

print(fn() or nil) returns only a

why? or should not matter since the first call was successful right?

Upvotes: 6

Views: 1086

Answers (1)

Yu Hao
Yu Hao

Reputation: 122363

Quoting from Programming in Lua §5.1 – Multiple Results

Lua always adjusts the number of results from a function to the circumstances of the call. When we call a function as a statement, Lua discards all results from the function. When we use a call as an expression, Lua keeps only the first result. We get all results only when the call is the last (or the only) expression in a list of expressions.

In the case of your example, the return value of fn() is used as an expression (the left operand of or operator), so only the first value is kept.

Upvotes: 6

Related Questions