Skip to content

Instantly share code, notes, and snippets.

@enghqii
Created May 7, 2017 16:25
Show Gist options
  • Save enghqii/29a150ac24ada280a385ea11a64de00c to your computer and use it in GitHub Desktop.
Save enghqii/29a150ac24ada280a385ea11a64de00c to your computer and use it in GitHub Desktop.
The art of computer programming vol.1 coroutine example in lua (3 passes)
INPUT = "A2B5E3426FG0ZYW3210PQ89R."
-- Registers
CH = nil
NUM = nil
COUNTER = 0
READ_INDEX = 1
WRITE_INDEX = 1
-- Coroutines
READ = coroutine.create(function()
for READ_INDEX = 1, #INPUT do
CH = INPUT:sub(READ_INDEX, READ_INDEX)
if CH ~= ' ' then
coroutine.yield(FILTER)
if CH == '.' then
print() -- line feed
break
end
end
end
end)
FILTER = coroutine.create(function()
while true do
NUM = tonumber(CH)
if NUM ~= nil then
NUM = NUM + 1
coroutine.yield(READ)
else
NUM = 1
end
coroutine.yield(WRITE)
end
end)
WRITE = coroutine.create(function()
while true do
for WRITE_INDEX = 1, NUM do
if COUNTER > 0 and COUNTER % 3 == 0 then
io.write(' ')
end
io.write(CH)
COUNTER = COUNTER + 1
end
coroutine.yield(READ)
end
end)
-- Dispatcher
CUR_ROUTINE = READ
while true do
local stat, val = coroutine.resume(CUR_ROUTINE)
CUR_ROUTINE = val
if CUR_ROUTINE == nil then break end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment