summaryrefslogtreecommitdiff
path: root/script/task.lua
blob: bb1a7922732bd4ad731ca363da171516db4457e1 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
local mt = {}
mt.__index = mt
mt.type = 'task'

function mt:remove()
    if self._removed then
        return
    end
    self._removed = true
    coroutine.close(self.task)
end

function mt:isRemoved()
    return self._removed
end

function mt:step()
    if self._removed then
        return
    end
    local suc, res = coroutine.resume(self.task)
    if not suc then
        self:remove()
        log.error(debug.traceback(self.task, res))
        return
    end
    if coroutine.status(self.task) == 'dead' then
        self:remove()
    end
    return res
end

function mt:fastForward()
    if self._removed then
        return
    end
    while true do
        local suc = coroutine.resume(self.task)
        if not suc then
            self:remove()
            break
        end
        if coroutine.status(self.task) == 'dead' then
            self:remove()
            break
        end
    end
end

function mt:set(key, value)
    self.data[key] = value
end

function mt:get(key)
    return self.data[key]
end

return function (callback)
    local self = setmetatable({
        data = {},
        task = coroutine.create(callback),
    }, mt)
    return self
end