Multiple return values ​​in Lua

Earlier this problem. For multiple return function

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

call

print(fn()) returns ab

but a challenge

print(fn() or nil) returns only a

why? or doesn't matter since the first call was successful correctly?

+6
source share
1 answer

Quoting from Programming in Lua Β§5.1 - Several results

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

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

+4
source

Source: https://habr.com/ru/post/958036/


All Articles