Examples of functions (function), variable parameters, local functions, and tail recursion optimization in Lua are explained _lua

Source: Internet
Author: User
Tags anonymous lua stdin

One, function

In Lua, a function is a "first class value" (first-class value), which means that a function can be stored in a variable, passed to another function by argument, or as a function's return value (analogous to a function pointer in C + +), which gives Lua great flexibility.

LUA provides good support for functional programming and can support nested functions.

In addition, LUA can invoke functions written by Lua and invoke functions written in C (all of the standard libraries in Lua are written in C).

Define a function

Copy Code code as follows:

function Hello ()
Print (' Hello ')
End

The Hello function does not receive parameters, called: Hello (), although Hello does not receive parameters, but can also pass in parameters: Hello (32)

In addition, if only one argument is passed, it can be simplified into the invocation form of functionname Arg (note that the value is not)

Copy Code code as follows:

> Hello ' 3 '
Hello
> Hello {}
Hello
> Hello 3
Stdin:1: Syntax error near ' 3 '


Also does not apply to variable names
Copy Code code as follows:

> A = 21
> Print a
Stdin:1: Syntax error near ' a '


In addition, the LUA function does not support parameter defaults and can be easily resolved using or (like JavaScript)
Copy Code code as follows:

> function f (n)
>> n = N or 0
>> print (n)
>> End
> f ()
0
> f (1)
1

LUA supports the return of multiple values, very similar in form to Python:

Copy Code code as follows:

> function f ()
>> return 1,2,3
>> End
> a,b,c = f ()
> Print (A... B. C)
123


The return value of a function call can be used for a table:
Copy Code code as follows:

> t = {f ()}
> Print (t[1], t[2], t[3])
1 2 3

Visible, the three values returned by F () are called the 3 elements of the table, but this is not always the case:
Copy Code code as follows:

> t = {f (), 4}
> Print (t[1], t[2], t[3])
1 4 Nil

This time, F () returns 1,2,3 only 1 elements called table;
Copy Code code as follows:

> t = {f (), F ()}
> Print (t[1], t[2], t[3], t[4], t[5]
1 1 2 3 nil


All in all: Only the last item will use all the return values (if it is a function call) completely.

For a function that has no return value, you can use the form (f ()) to forcibly return a value (nil)
Copy Code code as follows:

> function g ()
>> End
> Print (g ())

> Print ((g ())
Nil

In fact, a call in the form of (f ()) returns one and returns only one value
Copy Code code as follows:

> Print ((f ())
1
> Print (f ())
1 2 3

Second, variable length parameters

LUA supports programming parameters, simple to use (with table, multiple assignments)

Copy Code code as follows:

> function f (...)
For k,v in Ipairs ({...}) do
Print (K,V)
End
End
> f (2,3,3)
1 2
2 3
3 3

How to use multiple assignments
Copy Code code as follows:

> Function sum3 (...)
>> A,b,c = ...
>> A = A or 0
>> B = B or 0
>> C = C or 0
>> return a + b +c
>> End
> =sum3 (1,2,3,4)
6
> Return sum3 (1,2)
3

Typically, you only need to use {...} when traversing variable-length parameters, whereas variable-length parameters may contain some nil; then you can use the Select function to access variable-length arguments: Select (' # ', ...) or select (N, ...)

Select (' # ', ...) Returns the length of a variable parameter, select (n,...) Used to access N to select (' # ',...) The parameters

Copy Code code as follows:

> =select (' # ', 1,2,3)
3
> Return Select (' # ', 1,2, nil,3)
4
> =select (3, 1,2, nil,3)
Nil 3
> =select (2, 1,2, nil,3)
2 Nil 3

Note: Lua5.0 is not available in ... expression, but by an implied local table variable ARG to receive all the variable length parameters, ARG.N to represent the number of parameters;

Third, function-type programming

function to do a first-class value can be assigned to a variable, which is invoked

Copy Code code as follows:

> A = function () print ' Hello ' end
> A ()
Hello
> b = A
> B ()
Hello

anonymous functions
Copy Code code as follows:

> g = function () return function () print ' Hello ' end
> g () ()
Hello

function g returns an anonymous function;

Closures are an important feature of functional programming, and LUA supports
Copy Code code as follows:

> g = function (a) return function () print (' Hello ';. a); A = a + 1 end
> f = g (3)
> f ()
Hello3
> f ()
Hello4

Four, local functions

Local functions can be understood as functions that are valid in the current scope, and can be referenced by a global variable:

Copy Code code as follows:

> Do
>> Local LF = function () print ' Hello ' end
>> LF ()
>> End
Hello
> LF ()
Stdin:1: Attempt to call global ' LF ' (a nil value)
Stack Traceback:
Stdin:1: in main chunk
[C]: in?

It should be noted that for the processing of recursive functions

Copy Code code as follows:

> Do
Local LF = function (n)
If n <= 0 Then
Return
End
print ' Hello '
n = n-1
LF (n)
End
LF (3)
End
Hello
Stdin:8: Attempt to call global ' LF ' (a nil value)
Stack Traceback:
Stdin:8: in function ' LF '
Stdin:9: in main chunk
[C]: in?

Instead, you should first declare the local LF, which is assigned
Copy Code code as follows:

Todo
Local LF;
LF = function (n)
If n <= 0 Then
Return
End
print ' Hello '
n = n-1
LF (n)
End
LF (3)
End
Hello
Hello
Hello

LUA supports the definition of a local function (...). End:
Copy Code code as follows:

> Do
Local function LF (n)
If n <= 0 Then
Return
End
print ' Hello '
n = n-1
LF (n)
End
LF (3)
End
Hello
Hello
Hello
> LF (3)
Stdin:1: Attempt to call global ' LF ' (a nil value)
Stack Traceback:
Stdin:1: in main chunk
[C]: in?

Five, tail call

The so-called tail call is a function that returns the return value of another function:

Copy Code code as follows:

function f ()
...
return g ()
End

Because no code is executed in F () after the call to G (), there is no need to preserve the call 桟 information for f (); Lua did this optimization, called "Tail call elimination", where the control point returned directly to the call to F ().

This optimization is very useful for tail recursion, which usually means that the call to the 桟 is growing and may even result in a stack overflow, while tail recursion provides an optimization condition that the compiler can optimize out of call 桟.

The following recursive function does not use tail recursion, and when the argument is large, the stack overflows:
Copy Code code as follows:

> function f (n)
>> if n <= 0 Then
>> return 0
>> End
>> a = f (n-1)
>> return n * A
>> End
> f (10000000000)
Stdin:5: Stack Overflow
Stack Traceback:
Stdin:5: In function ' F '
Stdin:5: In function ' F '
Stdin:5: In function ' F '
Stdin:5: In function ' F '
Stdin:5: In function ' F '
Stdin:5: In function ' F '
Stdin:5: In function ' F '
Stdin:5: In function ' F '
Stdin:5: In function ' F '
Stdin:5: In function ' F '
...
Stdin:5: In function ' F '
Stdin:5: In function ' F '
Stdin:5: In function ' F '
Stdin:5: In function ' F '
Stdin:5: In function ' F '
Stdin:5: In function ' F '
Stdin:5: In function ' F '
Stdin:5: In function ' F '
Stdin:5: In function ' F '
Stdin:1: in main chunk
[C]: in?

Optimization for tail recursion
Copy Code code as follows:

function f (n, now)
If n <= 0 Then
Return to now
End

Return f (n-1, now*n)
End
F (10000000000, 1)

Run n long also no stack overflow;

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.