User:Iconmaster/rb.lua

From Esolang
Jump to navigation Jump to search

This is a program that implemets ] in Lua.

---------------------------
--
-- ] Interpreter
-- Made by Iconmaster
-- Implements ] programs.
--
---------------------------

function ex()
	print("Invalid ] Program!")
	--io.read()
	os.exit()
end

function check(orig)
	local inp
	inp = orig:gsub("%b()","")
	inp = inp:gsub("%b<>","")
	inp = inp:gsub("%b[]","")
	inp = inp:gsub("%b{}","")
	if orig:match("[%(%)]") and not inp:match("[%(%)]") then return false end
	if orig:match("[%<%>]") and not inp:match("[%<%>]") then return false end
	if orig:match("[%[%]]") and not inp:match("[%[%]]") then return false end
	if orig:match("[%{%}]") and not inp:match("[%{%}]") then return false end
	return true
end

if not args or not args[1] then
	io.write("Enter ] program:")
	inp = io.read("*l")
else
	inp = args[1]
end

if not check(inp) then ex() end
if inp:match("[^%(%)%<%>%{%}%[%]]") then ex() end

ptr = 1
stk = {}
mstk = {}
while true do
	if ptr > #inp then break end
	cmd = inp:sub(ptr,ptr)
	if cmd=="(" then
		table.insert(stk,true)
	elseif cmd==")" then
		table.insert(stk,false)
	elseif cmd=="<" then
		table.remove(stk)
	elseif cmd==">" then
		s1,s2 = table.remove(stk),table.remove(stk)
		table.insert(stk,s1)
		table.insert(stk,s2)
	elseif cmd=="{" then
		if stk[#stk] then
			level = 0
			repeat
				ptr = ptr + 1
				if inp:sub(ptr,ptr)=="{" then level = level + 1 end
				if inp:sub(ptr,ptr)=="}" then level = level - 1 end
			until level == -1
		end
	elseif cmd=="}" then
		if stk[#stk] then
			level = 0
			repeat
				ptr = ptr - 1
				if inp:sub(ptr,ptr)=="{" then level = level + 1 end
				if inp:sub(ptr,ptr)=="}" then level = level - 1 end
			until level == -1
		end
	elseif cmd=="[" then
		table.insert(mstk,stk)
		stk = {}
	elseif cmd=="]" then
		stk = {unpack(stk),unpack(table.remove(mstk))}
	end
end

--io.read()