1.1 實例代碼:
--迭代
local function enum(array)
local index = 1
return function()
local ret = array[index]
index = index + 1
return ret
end
end
local function foreach(array,action)
for element in enum(array)do
action(element)
end
end
foreach({1,2,3},print)
輸出結果:
1
2
3
1.2 有關迭代的描述:
迭代是for語句的一種特殊形式,可以通過for語句驅動迭代函數對一個給定集合進行遍歷。正式、完備的語法說明較復雜,請參考Lua手冊。
如前面代碼所示:enum函數返回一個匿名的迭代函數,for語句每次調用該迭代函數都得到一個值(通過element變量引用),若該值為nil,則for循環結束。
2.1 實例代碼
--線程
local function producer()
return coroutine.create(
function(salt)
local t = {1,2,3}
for i = 1,#t do
salt = coroutine.yield(t[i] + salt)
end
end
)
end
function consumer(prod)
local salt = 10
while true do
local running ,product = coroutine.resume(prod, salt)
salt = salt*salt
if running then
print(product or "END!")
else
break
end
end
end
consumer(producer())
輸出結果:
11
102
10003
END!
2.2 有關協作線程的描述:
通過coroutine.create可以創建一個協作線程,該函數接收一個函數類型的參數作為線程的執行體,返回一個線程對象。
通過coroutine.resume可以啟動一個線程或者繼續一個掛起的線程。該函數接收一個線程對象以及其他需要傳遞給該線程的參數。線程可以通過線程函數的參數或者coroutine.yield調用的返回值來獲取這些參數。當線程初次執行時,resume傳遞的參數通過線程函數的參數傳遞給線程,線程從線程函數開始執行;當線程由掛起轉為執行時,resume傳遞的參數以yield調用返回值的形式傳遞給線程,線程從yield調用后繼續執行
線程放棄調度
線程調用coroutine.yield暫停自己的執行,并把執行權返回給啟動/繼續它的線程;線程還可利用yield返回一些值給后者,這些值以resume調用的返回值的形式返回。
lua 論壇(lua 中國開發者 luaer中國官司方網站)
Lua參考手冊(最正式、權威的Lua文檔)
Lua編程(在線版,同樣具權威性的Lua教科書)
Lua正式網站的文檔頁面(包含很多有價值的文檔資料鏈接)
Lua維基(最全面的Lua維基百科)
LuaForge(最豐富的Lua開源代碼基地)
參考文獻《C/C++程序員的Lua快速入門》