71 lines
1.4 KiB
Lua
71 lines
1.4 KiB
Lua
local cp = 1
|
|
local data = {}
|
|
local dp = 1
|
|
local code = '[->+<]' -- add
|
|
data[1] = 3
|
|
data[2] = 4
|
|
--? local code = '++>++++[<+>-] # now print result\n ++++ ++++ [<+++ +++ > -] < .' -- add 2 to 5
|
|
--? local code = '++>++++[<+>-]<.'
|
|
|
|
function rfind(s, pat, i)
|
|
if i == nil then i = #s end
|
|
while i > 0 do
|
|
if s:sub(i,i) == pat then
|
|
return i
|
|
end
|
|
i = i-1
|
|
end
|
|
return nil
|
|
end
|
|
|
|
function eval()
|
|
print(cp, #code)
|
|
while cp <= #code do
|
|
local inst = code:sub(cp,cp)
|
|
if inst == '<' then
|
|
dp = dp-1
|
|
elseif inst == '>' then
|
|
dp = dp+1
|
|
elseif inst == '+' then
|
|
if data[dp] == nil then data[dp] = 0 end
|
|
data[dp] = data[dp]+1
|
|
elseif inst == '-' then
|
|
if data[dp] == nil then data[dp] = 0 end
|
|
data[dp] = data[dp]-1
|
|
elseif inst == '[' then
|
|
if data[dp] == 0 then
|
|
cp = code:find(']', cp)
|
|
end
|
|
elseif inst == ']' then
|
|
if data[dp] ~= 0 then
|
|
cp = rfind(code, '[', cp)
|
|
end
|
|
elseif inst == '.' then
|
|
print(string.char(data[dp]))
|
|
--? print(data[dp])
|
|
elseif inst == ',' then
|
|
data[dp] = string.byte(io.read(1))
|
|
elseif inst == '#' then
|
|
cp = code:find('\n', cp)
|
|
end
|
|
cp = cp+1
|
|
end
|
|
end
|
|
|
|
print(#arg)
|
|
if #arg > 0 then
|
|
print(arg[1])
|
|
local f = io.open(arg[1])
|
|
if f == nil then
|
|
print('could not open', arg[1])
|
|
os.exit(1)
|
|
end
|
|
code = f:read('*a')
|
|
eval()
|
|
end
|
|
|
|
print('---')
|
|
for i,n in ipairs(data) do
|
|
print(i,n)
|
|
end
|