-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathminiVM.lua
66 lines (56 loc) · 1.33 KB
/
miniVM.lua
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
-- 指令集
InstructionSet = {"PSH","ADD","POP","SET","HLT"}
Register = {A, B, C, D, E, F,NUM_OF_REGISTERS}
-- 测试程序代码
program = {"PSH", "5", "PSH", "6", "ADD", "POP", "HLT"}
-- 指令指针, 栈顶指针, 栈数组
IP = 1
SP = 0
stack = {}
-- 取指令函数
function fetch()
return program[IP]
end
-- 求值函数
function eval(instr)
if instr == "HLT" then
running = false
elseif instr == "PSH" then
-- 这里处理 PSH 指令, 具体处理如下
SP = SP + 1
-- 指令指针跳到下一个, 取得 PSH 的操作数
IP = IP + 1
stack[SP] = program[IP]
elseif instr == "POP" then
-- 这里处理 POP 指令, 具体处理后面添加
local val_popped = stack[SP]
SP = SP - 1
elseif instr == "ADD" then
-- 这里处理 ADD 指令, 具体处理如下
-- 先从栈中弹出一个值
local a = stack[SP]
stack[SP] = 0
SP = SP - 1
-- 再从栈中弹出一个值
local b = stack[SP]
stack[SP] = 0
SP = SP - 1
-- 把两个值相加
local result = a + b
-- 把相加结果压入栈中
SP = SP + 1
stack[SP] = result
-- 为方便查看测试程序运行结果, 这里增加一条打印语句
print(stack[SP])
end
end
-- 虚拟机主函数
function main()
running = true
while running do
eval(fetch())
IP = IP + 1
end
end
-- 启动虚拟机
main()