Functions in Lua

Source: Internet
Author: User

Objective

The functions in Lua are consistent with those in C + +, and the function format in Lua is as follows:

function MyFunc (param)      -- Do something End

When calling a function, you also need to put the corresponding argument in a pair of parentheses, even if there are no arguments when calling the function, you must write out a pair of empty parentheses. There is only one special exception to this rule: if a function has only one argument and this parameter is a string or table constructor, then the parentheses can be omitted. Look at the following code:

 print   "   Hello World   " -- > print (" Hello World ") equivalent  print   [[ a multi-line message  ]]  -- >print ([[A multi-line
     -- > m Essage]]) equivalent  --  F is a function  F{x=10 , Y=20 } --< /span>>f ({x=10, y=20}) equivalent  

Some of the simple wording of the above code, if unfamiliar, when reading someone's code, it will be confused.

A function definition has a name, a series of arguments, and a function body. When a function is defined, the parameters that are defined are used in a very similar way to local variables, which are initialized by the "actual arguments" when the function is called. The amount of real arguments provided when calling a function can be different from the amount of form parameters. LUA automatically adjusts the number of arguments to match the requirements of the parameter table, and if "arguments are superfluous, the extra arguments are discarded, and if the arguments are insufficient, the extra parameters are initialized to nil". This is very similar to the multiple return values to be introduced next.

"Multiple Return Values"

This should be a feature of Lua. Allows the function to return multiple results, simply listing all the return values after the return keyword. The following is a description of the situation according to the offer:

functionFoo0 ()End                         --no return valuefunctionFoo1 ()return "a" End          --Returns a resultfunctionFoo2 ()return "a","b" End     --returns two results--in multiple assignments, if a function call is the last, or only one, of the expression,--then Lua retains as many of its return values as possible to match the assignment variableX, y = Foo2 ()--x = "a", y = "B"x = Foo2 ()--x = "A", "B" is discardedX, y, z =Ten, Foo2 ()--x = ten, y = "a", z = "B"--If a function does not have a return value or if there are not enough return values, LUA uses--Nil to replenish the missing valuesX, y = Foo0 ()--x = nil, y = nilX, y = foo1 ()--x = "a", y = nilX, y, z = Foo2 ()--x = "a", y = "B", z = nil--If a function call is not the last element of a series of expressions, then only one value will be generated:X, y = Foo2 (), -          --x = "a", y =X, y = Foo0 (), -, -     --x = nil, y = 20, 30 is discarded--The table constructor can completely receive all the results of a function call, i.e. there will be no quantity--aspects of the adjustmentLocalt = {foo0 ()}--t = {} (an empty table)Localt = {foo1 ()}--T = {"A"}Localt = {Foo2 ()}--T = {"A", "B"}--However, for the above behavior, only occurs when a function call is the last element,--a function call in another location always produces only one result valueLocalt = {foo0 (), Foo2 (),4}--t[1] = nil, t[2] = "A", t[3] = 4--we can also use return to return the return value of another function in a functionfunctionMyFunc ()--returns a     returnFoo1 ()--Note: This is return foo1 () instead of return (FOO1 ())End--return Foo1 () and Return (Foo1 ()) are two completely different meanings--put a function call in a pair of parentheses, forcing it to return only one resultPrint((Foo0 ()))--NilPrint((Foo1 ()))--aPrint((Foo2 ()))--a

"Variable length parameter"

In C, functions can accept different numbers of arguments, and functions in Lua can accept different numbers of arguments, such as the following:

-- Print all the parameters function vararguments (...)       for inch Ipairs  do          Print (v)      End End vararguments (123)

3 points in the parameter table (...) ) indicates that the function can accept a different number of arguments. When this function is called, all its parameters are collected together. This part of the collected arguments is called the "variable length parameter" of the function. When a function accesses its variable length parameter, it still needs to use 3 points (...). )。 But the difference is that at this point the 3 points are used as an expression. In the example above, the expression {...} Represents an array of all variable-length parameters. The problem of using variable-length parameters in C requires attention in LUA as well.

Typically, a function simply iterates over its variable-length parameter by using the expression {...}, which accesses all variable-length parameters like a table. However, in some special cases, the variable length parameter may contain some intentionally passed nil, then you need to use Select to access the variable length parameter. When you call Select, you must pass in a fixed argument selector and a series of variable-length parameters. If selector is a number n, then select returns its nth variable argument and all arguments following it, otherwise selector can only be the string "#", so that select returns the total number of variable-length parameters, see the following code:

 for 1 Select ('#'    do Local Select -- get the first parameter    -- Do something else End

Select (' # ', ...) Returns the total number of all variable-length parameters, including nil (remember TABLE.MAXN?). For LUA version 5.0, the variable length parameter has a different set of mechanisms. The syntax for declaring a function is the same, and 3 points are used as the last parameter. But LUA 5.0 does not provide an "..." expression. Instead, an implicit local table variable "ARG" is adopted to accept all variable-length parameters. This table also has a field called "N", which is used to record the total number of variable-length parameters, such as the following code:

function MyFunc (A, B, ...)      Print (ARG.N) End MyFunc (12345)     -- >3

The disadvantage of this old mechanism is that every time a program invokes a function with a variable-length parameter, a new table is created. In the new mechanism, this table is created for variable-length parameter access only when needed. Here is just a simple introduction to this method, do not read other people's code, do not understand!!!

"In-depth discussion of functions"

In Lua, functions have the same rights as other traditional types of values. A function can be stored in a variable or table, passed as an argument to other functions, and can be used as a return value for other functions. There is a confusing notion in Lua that functions are as anonymous as all other values, that is, they do not have a name. When discussing a function name, you are actually discussing a variable that holds a function, such as the following code:

-- we often define functions like this function return 2 End -- in fact, it is just a kind of "grammatical sugar"; -- The above code is just a simplified form of writing for the following code function return 2 End

In fact, a function definition is actually a statement (more precisely an assignment statement), which creates a value of type "function" and assigns the value to a variable. Since the function is a normal value in Lua, it can be stored in a global variable and stored in a local variable or even in a table field.

"Inline Function"

If a function is written in another function, the inner function can access the local variable in the external function, which is called the lexical domain. Let's take a look at the following interesting code:

 function   Newcounter ()  local  i = 0  return  Span style= "COLOR: #0000ff" >function  () --  anonymous function  i = i + 1  return  
   
     i  
    end  
    end  Span style= "COLOR: #000000" >c1  =
     Newcounter ()  
    print      (C1 ()) 
    -- 
    > output what?  
    print  (C1 ()) 
    -- 
    > output? 
   

If you understand the above output and understand the above code, then the Closed function section does not need to be read. In the above code, there is a variable i, for the function newcounter, I is a local variable, but for the anonymous function, when it accesses the I, I is neither a global variable, nor a local variable, for us, we call such a variable is a "non-local variable." The following code is the same:

 function   Newcounter (i)  return  function  () --   anonymous function  i = i + 1  return   i  end  Span style= "COLOR: #0000ff" >end  c1  = Newcounter ( 10      )  print  (C1 ()) -- > output what?  print  (C1 ()) -- > output? 

The anonymous function accesses a "non-local variable" I, which is used to hold a counter. At first glance, since the function that creates the variable I, that is, Newcounter has returned, I should have gone beyond the scope of each call to the anonymous function. However, LUA correctly handles this situation with the closure concept. In a nutshell, a closure is a function plus all the "nonlocal variables" that the function needs to access. If you call Newcounter again, it will create a new local variable I, which will result in a new closure. In a follow-up summary, you are expected to summarize a blog post about closures in Lua.

"Non-global functions"

Because functions are the same as normal variables, functions can be stored not only in global variables, but also in fields in a table, or in local variables. We can put a function in a table, such as the following code:

Lib =functionreturnendfunctionreturnend

As long as a function is stored in a local variable, a "local function" is obtained, meaning that the function is valid only within a specific scope. We can define a local function in this way:

Local function (< parameters >)      < function body >end-  Lua also provides another special "syntax Sugar"localfunction F (< parameters >)      < function body >end

Sometimes, we need to make a pre-declaration of the function, such as the following code:

Local F, G function f ()      < some other operations >     g ()endfunction  g ()     < Some other operations >     F ()  End

Functions in Lua

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.