27 lines
1.1 KiB
Text
27 lines
1.1 KiB
Text
scope # Simple BF interpreter, based on the Lua sample: "Simple meta-implementation using load"
|
|
# reads the BF code from stdin, builds an equivalent Agena program and executes it
|
|
|
|
local constant bfOp := [ '>' ~ 'ptr +:= 1; '
|
|
, '<' ~ 'ptr -:= 1; '
|
|
, '+' ~ 'mem[ptr] +:= 1; '
|
|
, '-' ~ 'mem[ptr] -:= 1; '
|
|
, '[' ~ 'while mem[ptr] <> 0 do '
|
|
, ']' ~ 'od; '
|
|
, '.' ~ 'io.write(char(mem[ptr])); '
|
|
, ',' ~ 'mem[ptr] := abs(io.read(io.stdin,1) or "\\0"); '
|
|
];
|
|
|
|
local bfProgram := "local mem := setmetatable([], [ '__index' ~ proc() return 0 end ]);\n"
|
|
& "local ptr := 1;\n"
|
|
;
|
|
|
|
for line in io.lines() do
|
|
for p to size line do
|
|
local snippet := bfOp[ line[ p ] ];
|
|
if snippet then bfProgram &:= snippet & "\n" fi
|
|
od
|
|
od;
|
|
|
|
loadstring( bfProgram, "bfCode" )()
|
|
|
|
end
|