Lua Learning (4) -- Functions

Source: Internet
Author: User
Tags lua unpack

In Lua, the function call method is basically the same as that in C language, such as print ("Hello World") and a = add (x, y ). The only difference is that if a function has only one parameter and its type is String constant or table constructor, parentheses can be omitted, for example, print "Hello World" and f {x = 20, y = 20 }.
Lua provides a special syntax for Object-based calls-the colon operator. Another method of expression o. Foo (O, x) is O: Foo (X ). The colon operator calls O. Foo and uses O as the first parameter of the function.
The function declaration method in Lua is as follows:

  function add(a)        local sum = 0        for i, v in ipairs(a) do            sum = sum + v        end        return sum    end

1. Multiple results)

Lua allows multiple results of the function.

For example

s,e = string.find("hello lua world","lua")

 

function fun()     a="world"     b="hello"     return a,b endi,j=fun()print(i,j)

If the function does not return a value or does not have enough values, Lua uses nil to fill

1 x, y, z = fun () 2 Z value is nil

 

If a function call is not the last element of a series of expressions, only one value is generated:

X, Y = fun (), 20 -- X = "hello" Y = 20 -- fun () returns two values: "Hello" "world"

 

Force return an element with parentheses (fun ())

> function fun() a="hello" b="world" return a,b end> print((fun()))hello

The last one needs to introduce the Unpack function in Lua. This function will receive an array as a parameter and return all elements of the array starting from subscript 1. For example:

> print(unpack{10,20,30})10      20      30

An important use of the Unpack function is embodied in the generic call mechanism. The generic call mechanism can dynamically call a function using any real parameter.

For unpack usage, see http://www.cnblogs.com/corolla/p/3811793.html

 1 function fun(a,b)  2     if a>b then  3         print(a) 4     else  5        print(b)  6     end  7 end 8 tb={1,2} 9 fun(unpack(tb))10 2

 

When there are too many TB tables

tb={1,2,4}fun(unpack(tb))2

 

 

2. Variable Length Parameters

The function in Lua can accept different numbers of real parameters. For more information, see the following example:

function add(...)        local s = 0        for i,v in ipairs(...) do                s = s+v        --      print(v)        end        return sendtb={1,2,3,4}print(add(tb))

 

Local a, B =... similar to a function with multiple return values

 

 

> function fun(...) local a,b=... print(a,b) end > fun(2,4) 2 4

Access variable length... parameter, use the select function, access {...} is the same as access table. Select {"#",...} takes the total number of parameters, and local Arg = select {I,...} accesses the I. An example of traversal is as follows:

function fun(...)        local s=0        n = select("#",...)        for i=1, n do                local arg=select(i,...)                s = s+arg        end        return sendtb={1,2,3,4}print(fun(unpack(tb)))

 

 

3. Named real parameters:

The parameter transfer mechanism in Lua is location-based, that is, when calling a function, real parameters and form parameters must correspond one to one. Lua does not directly support this syntax, but it can get the same effect through a slight change. It organizes all real parameters into a table and passes the table as a unique real parameter to the function.

 tb={old="temp.lua",new="new.lua"} function rename(arg)   return os.rename(arg.old,arg.new)  end rename(tb)

 

If a function has a large number of parameters, most of which are optional, the method for passing the name parameter is very useful.

 

Deep understanding of functions

In Lua, a function is a "first-class value", which has a specific lexical domain (lexical scoping)

The first value indicates that the Lua function has the same rights as other traditional values. Functions can be stored in variables or tables. It can also be passed as a real parameter to other functions, or as the return value of other functions.

"Lexical domain" is a function that can escape from another function. Internal functions can access variables in external functions.

One confusing concept in Lua is that functions are anonymous like all other values, that is, they have no names. The function name is actually a variable of a function, and it is a truth to hold various values with other variables.

> TB = {P = print}> TB. P ("Hello World") Hello World> Print = math. sin -- print = sin function> TB. P (print (1) 0.8414709848079

 

 

4. Closure)

If you write a function in another function, the internal function can access the local variables in the external function.

newCounter = function(add)    local i = 0;    counter = function()        i = i + add        return i    end    return counterendc1 = newCounter(1)print(c1())1print(c1())2
 
  • The functions in Lua are "first-class values", that is, functions and integers. strings are the same and can be saved to variables. See the Declaration in the first sentence above.
  • It seems that the newcounter function that creates variable I has returned, so every time an anonymous function is called, I should be returned out of function. Otherwise, Lua uses the closure concept to handle this situation. A closure is a function and all the "non-local variables" It accesses ". In the preceding example, the non-local variables of the counter function are the I and add parameters. The values of these non-local variables can be obtained no matter how many times C1 accesses them.
 

5. Non-global functions

 

6. Tail call)

A feature of the Lua function is that Lua supports "Elimination of end calls": Elimination of end calls is a function call similar to goto. When another function g is called at the end of function f, it is called "tail call ". That is to say, after calling G, F function does not have other code to execute. In this case, the program does not need to save any stack information about function modification. The End call of Lua language does not consume any stack space.

Because the end call of the Lua function does not consume stack space, a program can have an infinite number of end calls.

Function f (x) g (x) end -- Not counting, g (x) must discard the temporary result return g (x) + 1 -- the addition return X or G (x) must be performed once. -- must be adjusted to a correct end call with the returned value: Return <function> (<ARGs>)

 

 

If there is no "tail call elimination", a new stack level will be created for each call ).

 

 

 

 

 

 

 

 

 

 

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.