Skip to content

Commit 1f8a3b0

Browse files
committed
Add interpreter example
1 parent df3ae34 commit 1f8a3b0

File tree

1 file changed

+37
-0
lines changed

1 file changed

+37
-0
lines changed

examples/04_interpreter.lua

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
local LuASM = require("luasm")
2+
3+
-- 1. Define the instruction set
4+
local instructions = {
5+
LuASM.instruction("print", { "string" }, {
6+
executor = function (instruction, _interpreter)
7+
print(instruction.args[1])
8+
end
9+
})
10+
}
11+
12+
-- 2. Create a runner (use default settings)
13+
local asm = LuASM:new(instructions, {
14+
syntax = {
15+
string = "^\"[%w]*\"",
16+
reg = "^%a[%w]*"
17+
}
18+
})
19+
20+
-- 3. Tokenize a source string
21+
local src = [[
22+
print "Hello"
23+
print "World"
24+
print "Message"
25+
]]
26+
local tokenizer = LuASM.string_tokenizer(src)
27+
28+
-- 4. Parse
29+
local result = asm:parse(tokenizer)
30+
31+
-- 5. Execution
32+
local interpreter = LuASM:interpreter(result)
33+
34+
interpreter:next_instruction()
35+
interpreter:next_instruction()
36+
interpreter:next_instruction()
37+

0 commit comments

Comments
 (0)