Instantly share code, notes, and snippets.

Embed
What would you like to do?
micro vm in lua
local MEM = {}
local PC = 0
local registers = {
A = 0,
B = 0,
C = 0,
D = 0
}
local fetch = function()
PC = PC + 1
return MEM[PC]
end
local operands = {
["0x00"] = "A",
["0x01"] = "B",
["0x02"] = "C",
["0x03"] = "D",
}
local opcodes = {
["0x00"] = function() -- NOP
end,
["0x01"] = function() -- MOV R, c
local A = operands[fetch()]
local c = fetch()
registers[A] = tonumber(c)
end,
["0x02"] = function() -- ADD R, r
local R = operands[fetch()]
local r = operands[fetch()]
registers[R] = registers[R] + registers[r]
end,
["0x03"] = function() -- SUB R, r
local R = operands[fetch()]
local r = operands[fetch()]
registers[R] = registers[R] - registers[r]
end,
["0x04"] = function() -- JMP addr
local addr = fetch()
PC = tonumber(addr)
end,
["0x05"] = function() -- IFE R, r
local R = registers[operands[fetch()]]
local r = registers[operands[fetch()]]
PC = (R == r) and PC + 3 or PC
end
}
local FDX = function()
print("PC", "IR", "A", "B")
while PC < #MEM do
local IR = fetch()
opcodes[IR]()
print(PC, IR, registers.A, registers.B, registers.C)
end
end
-- TEST machine
MEM = {
"0x00", -- NOP
"0x01", "0x01", "0x05", -- MOV B, 5
"0x01", "0x02", "0x01", -- MOV C, 1
"0x02", "0x00", "0x02", -- ADD A, C
"0x05", "0x00", "0x01", -- IFE A, B
"0x04", "0x7", -- JMP 1
"0x00",
"0x00"
}
FDX()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment