VM = {}
VM.Stack = [0,0,0,0,0,0,0,0,0,0]
VM.Insts = {}
VM.Insts.HALT = 0
VM.Insts.ADD = 1
VM.Insts.SUB = 2
VM.Insts.CONST = 3
VM.Insts.PRNT = 4
VM.Run = function(instrucs)
PC = 0
Stackp = -1
while true
inst = instrucs[PC]
if inst.opcode == self.Insts.HALT then
return
else if inst.opcode == self.Insts.ADD then
x = self.Stack[Stackp]
Stackp = Stackp - 1
y = self.Stack[Stackp]
self.Stack[Stackp] = x + y
else if inst.opcode == self.Insts.SUB then
x = self.Stack[Stackp]
Stackp = Stackp - 1
y = self.Stack[Stackp]
self.Stack[Stackp] = y - x
else if inst.opcode == self.Insts.CONST then
Stackp = Stackp + 1
self.Stack[Stackp] = inst.arg
else if inst.opcode == self.Insts.PRNT then
print(self.Stack[Stackp])
else
print(inst)
exit("Unknown opcode: " + i.opcode)
end if
PC = PC + 1
end while
end function
OS = []
OS.push({"opcode": VM.Insts.CONST, "arg": 23})
OS.push({"opcode": VM.Insts.CONST, "arg": 32})
OS.push({"opcode": VM.Insts.ADD, "arg": -1})
OS.push({"opcode": VM.Insts.PRNT, "arg": -1})
OS.push({"opcode": VM.Insts.CONST, "arg": 7})
OS.push({"opcode": VM.Insts.SUB, "arg": -1})
OS.push({"opcode": VM.Insts.PRNT, "arg": -1})
OS.push({"opcode": VM.Insts.HALT, "arg": -1})
print("Starting your personal Virtual Machine...")
VM.Run(OS)
print("Finished running your test!")