CloneTrooper1019

Brainfuck.lua

Feb 7th, 2019
469
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Lua 1.37 KB | None | 0 0
  1. local function brainFuck(data, input)
  2.     local pos = 1
  3.     local ptr = 0
  4.     local lvl = 0
  5.    
  6.     local ram = {}
  7.     local stack = {}
  8.    
  9.     local input = input or ""
  10.     local result = ""
  11.     local read = 1
  12.    
  13.     while pos <= #data do
  14.         if ram[ptr] == nil then
  15.             ram[ptr] = 0
  16.         end
  17.        
  18.         local cmd = data:sub(pos, pos)
  19.         local processed = true
  20.        
  21.         if cmd == '>' then
  22.             ptr = ptr + 1
  23.         elseif cmd == '<' then
  24.             ptr = ptr - 1
  25.         elseif cmd == '+' then
  26.             ram[ptr] = ram[ptr] + 1
  27.         elseif cmd == '-' then
  28.             ram[ptr] = ram[ptr] - 1
  29.         elseif cmd == '.' then
  30.             local byte = ram[ptr]
  31.             result = result .. string.char(byte)
  32.         elseif cmd == ',' then
  33.             local char = input:sub(read, read)
  34.             ram[ptr] = char:byte()
  35.             read = read + 1
  36.         elseif cmd == '[' then
  37.             if ram[ptr] > 0 then
  38.                 lvl = lvl + 1
  39.                 stack[lvl] = pos
  40.             else
  41.                 pos = select(2, data:find("%b[]", pos))
  42.             end
  43.         elseif cmd == ']' then
  44.             if ram[ptr] > 0 then
  45.                 pos = stack[lvl]
  46.             else
  47.                 lvl = lvl - 1
  48.             end
  49.         end
  50.        
  51.         pos = pos + 1
  52.     end
  53.    
  54.     print(result)
  55. end
Add Comment
Please, Sign In to add comment