In Lua, functions can return multiple values, in order to illustrate the number of return values in different cases, we declare the following functions first:
--No return value function Fun0 () end--a return value function Fun1 () return 1end--two return value function Fun2 () return 1, 2end--three and multiple return values function Fun3 ( ) return 1, 2, 3end
Typically, LUA automatically adjusts the number of valid return values based on the different circumstances of the function call. There are several main situations:
1. Call as a separate statement, discard all return values;
For example:
Fun0 () fun1 () fun2 () Fun3 ()
2. Invocation as an expression can be divided into two situations:
2.1 If you are in an expression string other than 2.2, only the first return value is returned;
For example:
if (fun2 () = = 1) then--returns only 1print (Fun2 ())--Print 1, 2 print (Fun2 (), "end")--print 1, "End"--if you want to force only one value to be returned, you can enclose the expression in parentheses "()": Print ((fun2 ()))--Printing 1end
2.2 In a multi-assignment, the return value is called as an argument to call other functions, in table, in the return statement, all the return values are valid if they are in the last expression;
For example:
In multiple assignments, if the function call is the only or last expression, return as many values as possible to match the left variable.
If it is extra, it is automatically discarded and, if not enough, is nil.
x = Fun0 ()--X = NILX = Fun1 ()--x = 1x = Fun2 ()--X = 1, 2 discard x = Fun3 ()--X = 1, 2, 3 discard x, y = fun1 ()--X = 1, y = ni LX, y = fun2 ()--X = 1, y = 2x, y = fun3 ()--X = 1, y = 2, 3 discard x, y, z = fun2 ()--X = 1, y = 2, z = nilx, y, z = fun3 () --X = 1, y = 2, z = 3
In addition, the function unpack can return multiple values, it passes in an array, and then returns each value in the array.
LUA Learning Note 14: function multiple return values