Lua Study Notes 14: multiple function return values, and lua Study Notes
The function in Lua can return multiple values. To illustrate the number of returned values in different cases, we first declare the following functions:
-- No return value function fun0 () end -- one return value function fun1 () return 1end -- two return values function fun2 () return 1, 2end -- three and multiple return values function fun3 () return 1, 2, 3end
Generally, Lua automatically adjusts the valid number of returned values based on different function calls. There are mainly the following situations:
1. If the call is used as a separate statement, all returned values are discarded;
For example:
fun0()fun1()fun2()fun3()
2. As an expression, a call can be divided into two situations:
2.1 if it is in the expression string except 2.2, only the first return value is returned;
For example:
If (fun2 () = 1) then -- only 1 print (fun2 () -- print 1, 2 print (fun2 (), "end") -- print 1, "end" -- if you want to forcibly return only one value, you can enclose the expression with brackets "()": print (fun2 () -- print 1end
2.2 When multiple values are assigned, the return value is used as the real parameter to call other functions. In table, if the return statement is in the last expression, all return values are valid;
For example:
In multi-value assignment, if a function call is used as the only or last expression, as many values as possible are returned to match the variable on the left,
If the number is large, it is automatically discarded. If not, it is assigned as 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 = nilx, 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, which are input into an array and then return each value in the array.