RosettaCodeData/Task/Execute-Brain-/Fennel/execute-brain-.fennel
2026-04-30 12:34:36 -04:00

34 lines
1.1 KiB
Fennel

(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 bf-op { ">" "ptr = ptr + 1"
"<" "ptr = ptr - 1"
"+" "mem[ptr] = mem[ptr] + 1"
"-" "mem[ptr] = mem[ptr] - 1"
"[" "while mem[ptr] ~= 0 do"
"]" "end"
"." "io.write(string.char(mem[ptr]))"
"," "mem[ptr] = string.byte(io.read(1) or \"\\0\")"
}
)
(var bf-program (.. "local mem = setmetatable({}, { __index = function() return 0 end })\n"
"local ptr = 1\n"
)
)
(each [line (io.lines)]
(for [p 1 (length line)]
(local op (. bf-op (line:sub p p)))
(when op
(set bf-program (.. bf-program op "\n"))
)
)
)
(local (bf-code msg) (load bf-program))
(if bf-code
(bf-code)
;else
(error msg)
)
)