-
-
Save nemesisqp/a0ee453cd3248369335a to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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