Lua programming in-depth function 01

Source: Internet
Author: User

In Lua, a function is a "first-class value", indicating that the function in Lua is the same as other traditional types of values (such as numbers and strings, it can be stored in variables (global, local) or tables, passed to other functions as real parameters, or returned values of other functions.

"Lexical domain": A function can be nested in another function, and internal functions can access variables in external functions.

Functions in Lua are anonymous like all other values. when discussing a function, we are actually discussing a variable holding a function. This is similar to the fact that variables hold various values and can be operated in multiple ways.

A = {P = print} A. P ("Hello World") ---> Hello worldprint = math. Sin ---> Print now references the sine function. A. P (print (1) ----> 0.841470sin = A. P ---> sin now references the print function. Sin (10, 20) ----> 10 20

A function in Lua can be understood as created by some expressions. Therefore, a function is actually a value assignment statement. This statement creates a value of the type "function, and assign this value to a variable.

 
Function Foo (x) return 2 * x end ====> Foo = function (x) return 2 * x end can convert the expression "function (X) <body> end "is regarded as a function constructor, just like the table constructor. The result of this function constructor is treated as an "anonymous function ".

Another function can be accepted as a real parameter, which is called a "high-order function ". Applying anonymous functions to create real parameters required by higher-order functions can bring more flexibility.

 
Function derivative (F, Delta) Delta = delta or Le-4 return function (x) Return (f (x + delta)-f (x )) /Delta end calls derivative (f) for a specific function f to return its derivative.

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.