coroutine
Lua提供coroutine的函式庫,使其有能力編寫不同模式的程式。
thread create
你可以透過coroutine.create()建立一個thread。
t1 = coroutine.create(function() print("Hello, World") end)
print(type(t1)) -- Output: thread
Lua並不是多執行緒的,其thread是輕量的。儘管Lua本身沒有異步(async)的寫法,但可以創造出異步的寫法。相對而言,值執行順序是明確許多的。
thread running
可以透過coroutine.resume()去觸發一個thread的執行:
coroutine.resume(t1) -- Output: Hello, World
傳入參數
可以對一個剛建立好的thread傳入參數。
function hello(name)
while true do
coroutine.yield("Hello, " .. name)
end
end
t1 = coroutine.create(hello)
print(coroutine.status(t1)) -- suspended
print(coroutine.resume(t1, "Bob")) -- Output: Hello, Bob
print(coroutine.status(t1)) -- suspended
print(coroutine.resume(t1, "World")) -- Output: Hello, Bob
thread close