LUA Learning Note 14: function multiple return values

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.