Advertisement
imring

[LUA] BrainFuck

Dec 20th, 2018
153
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Lua 1.24 KB | None | 0 0
  1. local sub, char, byte, match = string.sub, string.char, string.byte, string.match
  2.  
  3. local cpu = {}
  4.  
  5. local params = _ARGS
  6. if not params then return end
  7. local ret = ''
  8.  
  9. local text, chars = match(AnsiToUtf8(params), '(%S+)%s*(.*)')
  10.  
  11. local l, j, brc, i = 0, 0, 0, 0
  12.  
  13. local function getChar()
  14.   l = l + 1
  15.   return byte(chars, l)
  16. end
  17.  
  18. while #text > i do
  19.   i = i + 1
  20.   local ch = sub(text, i, i)
  21.   if ch == '>' then j = j + 1
  22.   elseif ch == '<' then j = j - 1
  23.   elseif ch == '+' then cpu[j] = ( cpu[j] or 0 ) + 1
  24.   elseif ch == '-' then cpu[j] = ( cpu[j] or 0 ) - 1
  25.   elseif ch == '.' then ret = ret .. char(cpu[j])
  26.   elseif ch == ',' then cpu[j] = getChar()
  27.   elseif ch == '[' then
  28.     if not cpu[j] or cpu[j] == 0 then
  29.       brc = brc + 1
  30.       while brc ~= 0 do
  31.         i = i + 1
  32.         local chh = sub(text, i, i)
  33.         if chh == '[' then brc = brc + 1
  34.         elseif chh == ']' then brc = brc - 1 end
  35.       end
  36.     end
  37.   elseif ch == ']' then
  38.     if cpu[j] and cpu[j] > 0 then
  39.       brc = brc + 1
  40.       while brc ~= 0 do
  41.         i = i - 1
  42.         local chh = sub(text, i, i)
  43.         if chh == '[' then brc = brc - 1
  44.         elseif chh == ']' then brc = brc + 1 end
  45.       end
  46.       i = i - 1
  47.     end
  48.   end
  49. end
  50.  
  51. return ret
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement