lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


I'm sorry, I just had to get this out of my system... appended is a Brainfuck 
compiler, written in Lua. Note that it's a *compiler*; it converts a BF 
program into a Lua chunk, and then runs it. It may even produce efficient 
code, but it's hard to tell.

It is, if I say so myself, really quite deranged. I've tried to produce a 
program that is worthy of both languages, with all that implies...



local t = {}; table.setn(t, 30000)
local n = 1;
local sg = string.gsub

function next(c) return function() n = n + 1; return c(); end; end
function prev(c) return function() n = n - 1; return c(); end; end
function inc(c) return function() t[n] = (t[n] or 0) + 1; return c(); end; end
function dec(c) return function() t[n] = (t[n] or 0) - 1; return c(); end; end
function o(c)
  return function() io.write(string.char(t[n] or 0)); return c(); end; end
function i(c)
  return function() t[n] = string.byte(io.read(1)); return c(); end; end
function l(c1, c2)
  return function() if (t[n] ~= 0) then c1()(); return l(c1, c2)(); else
    return c2(); end; end; end

function r(s, p, m) local n; s, n = sg(s, p, m)
  if (n ~= 0) then return r(s, p, m) end; return s; end

function trans(m, i, j, k, ...)
  m = r(m, "%"..i.."(.*)", j)
  if k then return trans(m, k, unpack(arg)); end
  return m
end

local bbn = 0
function bb(m)
  bbn = bbn + 1
  _G["bb"..(bbn-1)] = loadstring("return "..trans(m.."function() end", "+",
    "inc(%1)", "-", "dec(%1)", ".", "o(%1)", ",", "i(%1)", ">",
    "next(%1)", "<", "prev(%1)", "{", "l(%1", "}", ",%1)"))
  return "bb"..(bbn-1)
end

function luafuck(s)
  return _G[bb(r(sg(s, "[^+-<>[%]]", ""), "^(.*)%[([^%]]*)%](.*)$",
    function(sl, m, sr) return sl.."{"..bb(m).."}"..sr; end))]()
end

chunk = luafuck([[
++++++++++[>+++++++>++++++++++>+++>+<<<<-] >++.>+.+++++++..
+++.>++.<<+++++++++++++++.>.+++.------.--------.>+.>.
]])

chunk()

-- 
+- David Given --McQ-+ "I can handle myself. I've been in a fire fight.
|  dg@cowlark.com    | Well, I was in a fire.... Actually I was fired.
| (dg@tao-group.com) | From a fry cook opportunity." --- Firefly, _War
+- www.cowlark.com --+ Stories_

Attachment: pgp84FNuFnGqg.pgp
Description: PGP signature