Please note, this is a STATIC archive of website www.tutorialspoint.com from 11 May 2019, cach3.com does not collect or store any user information, there is no "phishing" involved.
local scheduler = {awaiting = {}}
local ts = 0;
local function current_timestamp()
return ts
end
-- ф-ция current_timestamp не существует, надо написать :)
function scheduler:resume_myself(ts)
local thread = coroutine.running()
table.insert(self.awaiting,
{thread = thread, ts = current_timestamp() + ts})
end
function scheduler:do_resume_thread(thread)
coroutine.resume(thread)
end
function scheduler:process_all_timeouts()
local to_delete = {}
for i, t in pairs(self.awaiting) do
if t.ts <= current_timestamp() then
self:do_resume_thread(t.thread)
table.insert(to_delete, i, 1) -- вставляем вначало
end
end
for _, v in ipairs(to_delete) do
table.remove(self.awaiting, i)
end
end
local eye = {}
function eye:close()
print(self, "close")
end
function eye:open()
print(self, "open", ts)
end
function eye:do_blink()
self:close()
scheduler:resume_myself(0.2)
coroutine.yield()
self:open()
end
function eye:blink()
local thread = coroutine.create(eye.do_blink)
coroutine.resume(thread, self)
end
function eye:new()
local t = {} -- наивная имплементация new
for n,v in pairs(self) do
t[n] = v
end
return t
end
local eyes = {
eye:new(),
eye:new()
}
--- main loop
for _, e in ipairs(eyes) do
e:blink()
end
-- время не прошло -- глаза ещё не откроются
scheduler:process_all_timeouts()
-- делаем вид, что часы тикают
ts = ts + 1
scheduler:process_all_timeouts()