1. 程式人生 > >Lua函數語言程式設計和區域性函式詳解

Lua函數語言程式設計和區域性函式詳解

         函數語言程式設計中的函式這個術語不是指計算機中的函式(實際上是Subroutine),而是指數學中的函式,即自變數的對映。也就是說一個函式的值僅決定於函式引數的值,不依賴其他狀態。比如sqrt(x)函式計算x的平方根,只要x不變,不論什麼時候呼叫,呼叫幾次,值都是不變的。

在函式式語言中,函式作為一等公民,可以在任何地方定義,在函式內或函式外,可以作為函式的引數和返回值,可以對函式進行組合。

函式做一個First-Class Value可以賦值給變數,用後者進行呼叫:

程式碼如下:

a = function() print 'hello' end
a()
hello
b = a
b()
hello

匿名函式

程式碼如下:

g = function() return function() print'hello' end end
g()()
hello

函式g返回一個匿名函式;

閉包是函數語言程式設計的一種重要特性,Lua也支援

程式碼如下:

g = function(a) return function()print('hello'.. a); a = a + 1 end end
f = g(3)
f()
hello3
f()
hello4

    區域性函式可以理解為在當前作用域有效的函式,可以用local變數來引用一個函式:

程式碼如下:

do
local lf = function() print 'hello' end
lf()
end
hello
lf()
stdin:1: attempt to call global 'lf' (a nilvalue)
stack traceback:
stdin:1: in main chunk
[C]: in ?

需要注意的是,對於遞迴函式的處理

程式碼如下:

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 nilvalue)
stack traceback:
stdin:8: in function 'lf'
stdin:9: in main chunk
[C]: in ?

而應該首先宣告local lf, 在進行賦值

程式碼如下:

do
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支援一種local function(…) … end的定義形式:

程式碼如下:

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 nilvalue)
stack traceback:
stdin:1: in main chunk
[C]: in ?