Created
January 24, 2023 07:26
-
-
Save ytaki0801/7aca2ad31d4f1a7cba16c0febd282f90 to your computer and use it in GitHub Desktop.
Brainf**k interpreter in Lua
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
codes = ""; f = io.input(arg[1]) | |
while true do | |
c = io.read(); if c == nil then break end | |
codes = codes..c | |
end | |
array = {}; p = 1; c = 1; cl = string.len(codes) | |
for i = 1, 65536 do array[i] = 0 end | |
while c <= cl do | |
c0 = string.sub(codes, c, c) | |
if c0 == '+' then array[p] = array[p] + 1 | |
elseif c0 == '-' then array[p] = array[p] - 1 | |
elseif c0 == '>' then p = p + 1 | |
elseif c0 == '<' then p = p - 1 | |
elseif c0 == '.' then io.write(string.char(array[p])) | |
elseif c0 == ',' then array[p] = tonumber(string.byte(io.read())) | |
elseif c0 == '[' then | |
if array[p] == 0 then | |
nest = 1 | |
while nest ~= 0 do | |
c = c + 1 | |
if string.sub(codes, c, c) == '[' then | |
nest = nest + 1 | |
end | |
if string.sub(codes, c, c) == ']' then | |
nest = nest - 1 | |
end | |
end | |
end | |
elseif c0 == ']' then | |
if array[p] ~= 0 then | |
nest = 1 | |
while nest ~= 0 do | |
c = c - 1 | |
if string.sub(codes, c, c) == ']' then | |
nest = nest + 1 | |
end | |
if string.sub(codes, c, c) == '[' then | |
nest = nest - 1 | |
end | |
end | |
end | |
end | |
c = c + 1 | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment