若是爲了更嚴格的使用局部變量,能夠用do-end來界定一個塊。即在do以後end以前組成一個做用域。數組
do local a = 10 ... end print( a ) -- nil
Lua中這個全局變量本質上也是一個table, 它把咱們建立的全局變量都保存在一個table裏了。這個table名爲_G。因此咱們能夠這樣返回全局變量:閉包
print( _G["myGlobal"] ) -- 這個全局名固然能夠是其餘類型 print( _G.myGlobal )
在多重返回值中,unpack,它接受一個數組爲參數,它返回下標爲1開始的全部元素。函數
local function Foo(a, b) print(a, b) end local tab = {1,2} Foo(unpack(tab)) -- 1,2
function add(...) local s = 0 for i, v in ipairs{...} do s = s + v end return s end print( add(2,3,3) ) -- 8
參數表三個點表示可接受不一樣數量的實參。lua
function Add(options) if type(options.num1) ~= "number" or type(options.num2) ~= "number" then error("Add parameter are not number type") end print(options.num1, options.num2) end Add{num2=5,num1=4} -- 使用具名實參
foo = function (x) return 2*x end -- 匿名函數 -- 使用匿名函數增長便捷性 table.sort( network, function (a,b) return a.name > b.name end ) -- 用閉包實現一個計數函數 function newCounter() local iCount = 0 return function () iCount = iCount + 1 return iCount end end c1 = newCounter() print( c1() ) -- 1 print( c1() ) -- 2 c2 = newCounter() print( c2() ) -- 1 print( c1() ) -- 3 print( c2() ) -- 2 -- 閉包實現迭代器(更準確說是生成器) function next(t) local i = 0 return function () i = i + 1; return t[i] end end t = {1,2,10} iter = next(t) while true do local elem = iter() if elem == nil then break end print(elem) end tt = {10,11,13} for elem in next(tt) do print(elem) end
當一個函數調用另外一個函數的最後一個動做時,該調用就算是一條尾調用。code
尾調用不耗費任何棧空間,故在遞歸函數裏使用尤現優點。遞歸
function f(x) return g(x) end -- 尾調用 -- 任何數字做爲參數都不會形成棧溢出 function goo(n) if n > 0 then return goo(n-1) end end -- 如下都是不尾調用,只有符合「return <func>(<args>)」纔算尾調用 function f(x) g(x) end return g(x) + 1 return g(x) or x return (g(x)) -- 這種複雜的算尾調用 return x[i].foo(x[j]+ a*b, i+j)
function func(x) x = x or 0 -- 可是要注意,若是參數用布爾值,不能這麼用 end