-
Notifications
You must be signed in to change notification settings - Fork 1
/
vm.go
80 lines (65 loc) · 1.32 KB
/
vm.go
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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
package js
import (
"github.com/mangalorg/luaprovider/util"
"github.com/robertkrimen/otto"
lua "github.com/yuin/gopher-lua"
)
const vmTypeName = libName + "_vm"
func pushVM(L *lua.LState, vm *otto.Otto) {
ud := L.NewUserData()
ud.Value = vm
L.SetMetatable(ud, L.GetTypeMetatable(vmTypeName))
L.Push(ud)
}
func checkVM(L *lua.LState, n int) *otto.Otto {
ud := L.CheckUserData(n)
if v, ok := ud.Value.(*otto.Otto); ok {
return v
}
L.ArgError(n, "js_vm expected")
return nil
}
func newVM(L *lua.LState) int {
vm := otto.New()
pushVM(L, vm)
return 1
}
func vmRun(L *lua.LState) int {
vm := checkVM(L, 1)
script := L.CheckString(2)
value, err := vm.Run(script)
if err != nil {
L.RaiseError(err.Error())
return 0
}
util.Push(L, &value, valueTypeName)
return 1
}
func vmGet(L *lua.LState) int {
vm := checkVM(L, 1)
name := L.CheckString(2)
value, err := vm.Get(name)
if err != nil {
L.RaiseError(err.Error())
return 0
}
util.Push(L, &value, valueTypeName)
return 1
}
func vmSet(L *lua.LState) int {
vm := checkVM(L, 1)
name := L.CheckString(2)
lvalue := L.CheckAny(3)
value, err := util.FromLValue(lvalue)
if err != nil {
L.Push(lua.LString(err.Error()))
L.RaiseError(err.Error())
return 0
}
err = vm.Set(name, value)
if err != nil {
L.RaiseError(err.Error())
return 0
}
return 0
}