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.