]>
Commit | Line | Data |
---|---|---|
a098bb43 CP |
1 | local sched = {} |
2 | local tag = 0 | |
3 | ||
4 | local function timesort(a, b) | |
5 | return a[1] < b[1] | |
6 | end | |
7 | ||
8 | function doschedule() | |
9 | local ct = os.time() | |
10 | local out = {} | |
11 | local callers = {} | |
12 | ||
13 | for t, e in pairs(sched) do | |
14 | if t <= ct then | |
15 | table.insert(callers, { t, e }) | |
16 | else | |
17 | out[t] = e | |
18 | end | |
19 | end | |
20 | table.sort(callers, timesort) | |
21 | ||
22 | sched = out | |
23 | ||
24 | for _, e in ipairs(callers) do | |
25 | for _, v in pairs(e[2]) do | |
26 | if v[1] then | |
27 | if v[2] then | |
28 | v[1](unpack(v[2])) | |
29 | else | |
30 | v[1]() | |
31 | end | |
32 | else | |
33 | scripterror("schedule.lua: event is nil!") | |
34 | end | |
35 | end | |
36 | end | |
37 | end | |
38 | ||
39 | function schedule(when, callback, ...) | |
40 | tag = tag + 1 | |
41 | local n = { callback, { ... }, tag } | |
42 | local w = os.time() + when | |
43 | ||
44 | if sched[w] then | |
45 | table.insert(sched[w], n) | |
46 | else | |
47 | sched[w] = { n } | |
48 | end | |
49 | return { w, tag } | |
50 | end | |
51 | ||
52 | function delschedule(tag) | |
53 | local c = {} | |
54 | ||
55 | local w, o = unpack(tag) | |
56 | if not sched[w] then | |
57 | return | |
58 | end | |
59 | ||
60 | for i, v in pairs(sched[w]) do | |
61 | if v[3] == o then | |
62 | if #sched[w] == 1 then | |
63 | sched[w] = nil | |
64 | else | |
65 | sched[w][i] = nil | |
66 | end | |
67 | return | |
68 | end | |
69 | end | |
70 | end | |
71 | ||
72 | function scheduleempty() | |
73 | return tableempty(sched) | |
74 | end |