-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathbrainfuck.lua
More file actions
60 lines (58 loc) · 1.82 KB
/
brainfuck.lua
File metadata and controls
60 lines (58 loc) · 1.82 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
function readfile(path)
local f = io.open(path, "r")
local content = f:read("*all")
f:close()
return content
end
function runbrainfuck(code)
local data = {}
for i = 1, 30000 do
data[i] = 0
end
local len = code:len()
local dptr = 1
local iptr = 1
while iptr < len do
local count = 1
if code:sub(iptr, iptr) == '>' then
dptr = dptr + 1
elseif code:sub(iptr, iptr) == '<' then
dptr = dptr - 1
elseif code:sub(iptr, iptr) == '+' then
data[dptr] = data[dptr] + 1
elseif code:sub(iptr, iptr) == '-' then
data[dptr] = data[dptr] - 1
elseif code:sub(iptr, iptr) == '.' then
io.write(string.char(data[dptr]))
elseif code:sub(iptr, iptr) == ',' then
data[dptr] = string.byte(io.read(1))
elseif code:sub(iptr, iptr) == '[' then
if data[dptr] == 0 then
iptr = iptr + 1
while count > 0 do
if code:sub(iptr, iptr) == '[' then
count = count + 1
elseif code:sub(iptr, iptr) == ']' then
count = count -1
end
iptr = iptr + 1
end
iptr = iptr + 1
end
elseif code:sub(iptr, iptr) == ']' then
if data[dptr] ~= 0 then
iptr = iptr - 1
while count > 0 do
if code:sub(iptr, iptr) == ']' then
count = count + 1
elseif code:sub(iptr, iptr) == '[' then
count = count - 1
end
iptr = iptr - 1
end
end
end
iptr = iptr + 1
end
end
runbrainfuck(readfile(arg[1]))