41 lines
1.8 KiB
Lua
41 lines
1.8 KiB
Lua
local registers = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0}
|
|
local r = registers
|
|
for _,path in pairs({...}) do
|
|
local file = io.open(path)
|
|
if not file then error("Could not open: "..path) end
|
|
local content = file:read("*a")
|
|
local index = 1
|
|
local instructions = {
|
|
["add (%d+) (%d+) (%d+)"] = function(d,a,b) r[d + 1] = r[a + 1] + r[b + 1] end,
|
|
["sub (%d+) (%d+) (%d+)"] = function(d,a,b) r[d + 1] = r[a + 1] - r[b + 1] end,
|
|
["mul (%d+) (%d+) (%d+)"] = function(d,a,b) r[d + 1] = r[a + 1] * r[b + 1] end,
|
|
["shl (%d+) (%d+)"] = function(d,a,b) r[d + 1] = r[d + 1] << r[a + 1] end,
|
|
["shr (%d+) (%d+)"] = function(d,a,b) r[d + 1] = r[d + 1] >> r[a + 1] end,
|
|
["bor (%d+) (%d+)"] = function(d,a,b) r[d + 1] = r[a + 1] | r[b + 1] end,
|
|
["band (%d+) (%d+)"] = function(d,a,b) r[d + 1] = r[a + 1] & r[b + 1] end,
|
|
["li (%d+) (%d+)"] = function(d,i) r[d + 1] = i end,
|
|
["jz (%d+) (%d+)"] = function(d,a,i) if r[a + 1] == 0 then index = index + r[i + 1] - 1 end end,
|
|
["jp (%d+) (%d+)"] = function(d,a,i) if r[a + 1] > 0 then index = index + r[i + 1] - 1 end end,
|
|
["TELL (%d+)"] = function(r) print(" ",registers[r]) end, -- DEBUGGING, NOT IN FUNNYCORE!!!
|
|
["PUT (.+)"] = function(r) end,
|
|
["HALT"] = function(r) index = -1 end
|
|
}
|
|
local lines = {}
|
|
for line in content:gmatch("[^\n\r]+") do table.insert(lines,line) end
|
|
local function execute_instruction(line)
|
|
for pattern,callback in pairs(instructions) do
|
|
local result = {}
|
|
for index,item in pairs({line:match(pattern)}) do
|
|
table.insert(result,tonumber(item))
|
|
end
|
|
if #result ~= 0 then
|
|
callback(table.unpack(result))
|
|
end
|
|
end
|
|
end
|
|
while lines[index] do
|
|
print(lines[index],string.format("R{%s}",table.concat(registers,",")))
|
|
execute_instruction(lines[index])
|
|
index = index + 1
|
|
end
|
|
end
|