Script kiddie _Lua deep dive into functions

1. Function

Functions can be stored in variables (regardless of global or local variables) or tables, can be passed as arguments to other functions, and can also be used as return values ​​of other functions
1.1. Examples
print("xiaobei")
p = print
p('123456')
From the running result of this example, 123456 can be printed normally. It is equivalent to the variable p, which is the same as the function print.
1.2. Examples
p = function (str)
print(str)
end
p('haha')
This statement creates a value of type "function" and assigns this value to a variable. This expression can be thought of as a functional construct. and call its result an "anonymous function"

2. Closure
Functions can be nested within another function, and the inner function can access variables in the outer function
2.1. Examples
function newCounter()
local i = 0
return function()
i = i + 1
return i
end
end
c1 = newCounter()
print(c1())
print(c1())

c2 = newCounter()
print(c2())
print(c1())
From the running results of this example, it can be concluded that a closure is a function plus all the "non-local variables" that the function needs to access. If newCounter is called again, a new local variable i will be created, resulting in a new closure



Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325647793&siteId=291194637