-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.go
More file actions
50 lines (42 loc) · 948 Bytes
/
Copy pathmain.go
File metadata and controls
50 lines (42 loc) · 948 Bytes
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
// Example: Basic Lua execution
//
// This example shows the simplest way to run Lua code from Go.
package main
import (
"fmt"
"log"
"github.com/iceisfun/golua/v2/compiler"
"github.com/iceisfun/golua/v2/parser"
"github.com/iceisfun/golua/v2/stdlib"
"github.com/iceisfun/golua/v2/vm"
)
func main() {
// Lua source code
source := `
local function factorial(n)
if n <= 1 then return 1 end
return n * factorial(n - 1)
end
return factorial(10)
`
// Parse
block, err := parser.Parse("factorial", source)
if err != nil {
log.Fatalf("Parse error: %v", err)
}
// Compile
proto, err := compiler.Compile("factorial", block)
if err != nil {
log.Fatalf("Compile error: %v", err)
}
// Create VM with standard library
v := vm.New()
stdlib.Open(v)
// Run
results, err := v.Run(proto)
if err != nil {
log.Fatalf("Runtime error: %v", err)
}
// Print result
fmt.Printf("factorial(10) = %v\n", results[0].AsInt())
}