27 lines
1.1 KiB
Text
27 lines
1.1 KiB
Text
do -- Simple BF interpreter, based on the Lua sample: "Simple meta-implementation using load"
|
|
-- reads the BF code from stdin, builds an equivalent Pluto program and executes it
|
|
|
|
local bfOp <const> = { ['>'] = 'ptr += 1 '
|
|
, ['<'] = 'ptr -= 1 '
|
|
, ['+'] = 'mem[ptr] += 1 '
|
|
, ['-'] = 'mem[ptr] -= 1 '
|
|
, ['['] = 'while mem[ptr] != 0 do '
|
|
, [']'] = 'end '
|
|
, ['.'] = 'io.write(string.char(mem[ptr])) '
|
|
, [','] = 'mem[ptr] = string.byte(io.read(1) ?? "\\0") '
|
|
};
|
|
|
|
local bfProgram = "local mem = setmetatable({}, { __index = function() return 0 end })\n"
|
|
.. "local ptr = 1\n"
|
|
|
|
for line in io.lines() do
|
|
for p = 1, # line do
|
|
local snippet = bfOp[ line[ p ] ]
|
|
if snippet then bfProgram ..= snippet .. "\n" end
|
|
end
|
|
end
|
|
|
|
local bfCode, msg = load( bfProgram )
|
|
if bfCode then bfCode() else error( msg ) end
|
|
|
|
end
|