Jump to content

Execute Brain****/Lua: Difference between revisions

Fixed bracket matching and made them a bit more robust.
No edit summary
(Fixed bracket matching and made them a bit more robust.)
Line 1:
{{implementation|Brainf***}}{{collection|RCBF}}
 
{{incorrect|Lua|Instead of jumping to the *next* close bracket when reaching a [ and memory[pointer] == 0, it should jump to the next *matching* close bracket such that embedded loops work}}
An implementation of a Brainf*** interpreter in [[Lua]].
<lang lua>memory = {0} --memory is bounded on one side, at 1
Line 30:
if memory[pointer] ~= 0 then
table.insert(retpoints, instruction)
else -- if the memory at the pointer is zero, jump to the nextmatching close bracket
local b = 1 -- b stores number of unclosed brackets (when b == 0 the match has been found)
while program:sub(instruction, instruction) ~= "]" do
while instruction <= #program and b ~= 0 do
instruction = instruction + 1
while if program:sub(instruction, instruction) ~== "][" dothen
b = b + 1
elseif program:sub(instruction, instruction) == "]"
b = b - 1
end
end
if b ~= 0 then
error"Missing ']'!"
end
end
end,
["]"] = function()
if memory[pointer]#retpoints ~=> 0 then
if memory[pointer] ~= 0 then
instruction = retpoints[#retpoints]
else
table.remove(retpoints)
end
else
error"Missing '['!"
table.remove(retpoints)
end
end,
Anonymous user
Cookies help us deliver our services. By using our services, you agree to our use of cookies.