Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple return values in Lua

Tags:

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?

like image 869
Antony Thomas Avatar asked Nov 14 '13 02:11

Antony Thomas


People also ask

How do I return a value in Lua?

Function return values In most languages, functions always return one value. To use this, put comma-separated values after the return keyword: > f = function () >> return "x", "y", "z" -- return 3 values >> end > a, b, c, d = f() -- assign the 3 values to 4 variables.

What is unpack Lua?

In Lua, if you want to call a variable function f with variable arguments in an array a , you simply write f(unpack(a)) The call to unpack returns all values in a , which become the arguments to f .

How do I comment multiple lines in Lua?

A comment starts with a double hyphen ( -- ) anywhere outside a string. They run until the end of the line. You can comment out a full block of code by surrounding it with --[[ and --]] . To uncomment the same block, simply add another hyphen to the first enclosure, as in ---[[ .

What does three dots mean in Lua?

The three dots ( ... ) in the parameter list indicate that the function has a variable number of arguments. When this function is called, all its arguments are collected in a single table, which the function accesses as a hidden parameter named arg .


1 Answers

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.

like image 192
Yu Hao Avatar answered Nov 12 '22 06:11

Yu Hao