-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathex24.3.lua
More file actions
80 lines (76 loc) · 1.95 KB
/
ex24.3.lua
File metadata and controls
80 lines (76 loc) · 1.95 KB
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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
local cmdQueue = {}
-- queue of pending operations
local lib = {}
function lib.readline (stream, callback)
local nextCmd = function ()
callback(stream:read())
end
table.insert(cmdQueue, nextCmd)
end
function lib.writeline (stream, line, callback)
local nextCmd = function ()
callback(stream:write(line))
end
table.insert(cmdQueue, nextCmd)
end
function lib.stop ()
table.insert(cmdQueue, "stop")
end
function lib.runloop ()
while true do
local nextCmd = table.remove(cmdQueue, 1)
if nextCmd == "stop" then
break
else
nextCmd()
-- perform next operation
end
end
end
-- return lib
--------------------------------------------------------------------------------
local function run (code)
local co = coroutine.wrap(function ()
code()
lib.stop()
-- finish event loop when done
end)
co()
-- start coroutine
lib.runloop()
-- start event loop
end
local put_mem = { }
local function putline (stream, line)
local co = coroutine.running()
-- calling coroutine
-- local callback = (function () coroutine.resume(co) end)
local callback = put_mem[co] or (function () coroutine.resume(co) end)
put_mem[co] = callback
lib.writeline(stream, line, callback)
coroutine.yield()
end
local get_mem = { }
local function getline (stream)
local co = coroutine.running()
-- calling coroutine
-- local callback = (function (l) coroutine.resume(co, l) end)
local callback = get_mem[co] or (function (l) coroutine.resume(co, l) end)
get_mem[co] = callback
lib.readline(stream, callback)
local line = coroutine.yield()
return line
end
run(function ()
local t = {}
local inp = io.open("ex24.3.lua")
local out = io.output()
while true do
local line = getline(inp)
if not line then break end
t[#t + 1] = line
end
for i = #t, 1, -1 do
putline(out, t[i] .. "\n")
end
end)