示例工程 22-scheduling-and-tasks
22-scheduling-and-tasks/02-cancel-and-timeout/main.lua
-- @runtimes lua54 luajit
--- 演示:取消标志与超时。
local M = {}
local function task(state)
while not state.cancelled do
state.ticks = state.ticks + 1
coroutine.yield(state.ticks)
end
return "cancelled"
end
--- @return table { ticks = integer, stopped = boolean }
function M.run(log)
log = log or print
local state = { cancelled = false, ticks = 0 }
local co = coroutine.create(task)
local ticks = 0
while ticks < 3 do
local ok, value = coroutine.resume(co, state)
assert(ok, value)
ticks = value
end
state.cancelled = true
local ok, value = coroutine.resume(co, state)
assert(ok, value)
log(("ticks=%d stopped=%s"):format(state.ticks, tostring(value == "cancelled")))
return { ticks = state.ticks, stopped = value == "cancelled" }
end
if not ... then
M.run()
end
return M