Advertisement
alamo564

[Lua] Brainfuck

Dec 30th, 2020
78
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Lua 1.39 KB | None | 0 0
  1. local memory = {}
  2. local pointer = 0
  3. local offset = 1
  4. local loop = 0
  5. local canRead = true
  6.  
  7. local output = {}
  8. local source = "++++++++++[>++++++++>++++++++++>+++++++++++>++++++++++++>++++++++++>+++<<<<<<-]>++++.>+.>+++++.>----.>+.>+++."
  9.  
  10. -- Definir os tokens
  11. local tokens = {
  12.     ["+"] = function()
  13.         if canRead then
  14.             memory[pointer] = (memory[pointer] + 1) % 256
  15.         end
  16.     end,
  17.    
  18.     ["-"] = function()
  19.         if canRead then
  20.             memory[pointer] = (memory[pointer] - 1) % 256
  21.         end
  22.     end,
  23.    
  24.     [">"] = function()
  25.         if canRead then
  26.             pointer = pointer + 1
  27.         end
  28.     end,
  29.    
  30.     ["<"] = function()
  31.         if canRead then
  32.             pointer = pointer - 1
  33.         end
  34.     end,
  35.    
  36.     ["."] = function()
  37.         if canRead then
  38.             table.insert(output, string.char(memory[pointer]))
  39.         end
  40.     end,
  41.    
  42.     ["["] = function()
  43.         loop = offset - 1
  44.         canRead = memory[pointer] > 0
  45.     end,
  46.    
  47.     ["]"] = function()
  48.         offset = canRead and loop or offset
  49.         canRead = true
  50.     end
  51. }
  52.  
  53. -- Inicializar a memória
  54. for i = pointer, 1024 do
  55.     memory[i] = 0
  56. end
  57.  
  58. -- Ler cada um dos caracteres
  59. while offset <= source:len() do
  60.     local character = source:sub(offset, offset)
  61.     local token = tokens[character]
  62.    
  63.     if token then
  64.         token()
  65.     end
  66.    
  67.     offset = offset + 1
  68. end
  69.  
  70. -- Escrever a output
  71. print(table.concat(output))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement