Skip to content

Instantly share code, notes, and snippets.

@pingbird
Created March 28, 2014 06:48
Show Gist options
  • Save pingbird/9826754 to your computer and use it in GitHub Desktop.
Save pingbird/9826754 to your computer and use it in GitHub Desktop.
Befunge
local prg='0"!dlroW ,olleH">:#,_@'
local mem={}
local width=0
local sy=0
local stack={}
local function push(val)
table.insert(stack,1,val%256)
end
local function pop(n)
local v=stack[n or 1]
table.remove(stack,n or 1)
return v
end
for line in prg:gmatch("[^\n]+") do
sy=sy+1
width=math.max(width,#line)
mem[sy]={string.byte(line,1,#line)}
end
for ly=1,sy do
for lx=1,width do
mem[ly][lx]=mem[ly][lx] or 32
end
end
local x=1
local y=1
local dir=2
local dirs={
["^"]=1,
[">"]=2,
["v"]=3,
["<"]=4,
}
local strmode=false
while (mem[y] or {})[x] do
local ins=string.char(mem[y][x])
if strmode then
if ins=="\"" then
strmode=false
else
push(mem[y][x])
end
else
if ins=="+" then
push(pop()+pop())
elseif ins=="-" then
push(pop(2)-pop())
elseif ins=="*" then
push(pop(2)*pop())
elseif ins=="/" then
push(math.floor(pop(2)/pop()))
elseif ins=="%" then
push(pop(2)%pop())
elseif ins=="!" then
push(pop()==0 and 1 or 0)
elseif ins=="`" then
push(pop()>pop() and 1 or 0)
elseif dirs[ins] then
dir=dirs[ins]
elseif ins=="?" then
dir=math.random(1,4)
elseif ins=="_" then
dir=pop()==0 and 2 or 4
elseif ins=="|" then
dir=pop()==0 and 3 or 1
elseif ins=="\"" then
strmode=true
elseif ins==":" then
push(stack[1])
elseif ins=="\\" then
stack[1],stack[2]=stack[2],stack[1]
elseif ins=="$" then
pop()
elseif ins=="." then
io.write(pop())
elseif ins=="," then
io.write(string.char(pop()))
elseif ins=="#" then
x=x+(({[4]=-1,[2]=1})[dir] or 0)
y=y+(({[1]=-1,[3]=1})[dir] or 0)
elseif ins=="g" then
push((mem[pop()] or {})[pop()] or 32)
elseif ins=="p" then
(mem[pop(2)] or {})[pop(2)]=pop()
elseif ins=="&" then
push(tonumber(io.read()))
elseif ins=="~" then
push(string.byte(io.read(1)))
elseif ins=="@" then
return
elseif tonumber(ins) then
push(tonumber(ins))
end
end
x=x+(({[4]=-1,[2]=1})[dir] or 0)
y=y+(({[1]=-1,[3]=1})[dir] or 0)
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment