-
Notifications
You must be signed in to change notification settings - Fork 1
/
lua_state.go
74 lines (58 loc) · 1.27 KB
/
lua_state.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
package lua
import (
"errors"
"fmt"
"strconv"
"sync"
"unsafe"
)
// #cgo LDFLAGS: -lluajit-5.1 -ldl -lm
//#include "glua.h"
import "C"
var (
rw sync.RWMutex
luaStateCache map[int64]*C.struct_lua_State
)
func init() {
luaStateCache = make(map[int64]*C.struct_lua_State)
}
func generateLuaStateId(vm *C.struct_lua_State) int64 {
ptr := unsafe.Pointer(vm)
vmKey, _ := strconv.ParseInt(fmt.Sprintf("%d", ptr), 10, 64)
return vmKey
}
func createLuaState() (int64, *C.struct_lua_State) {
vm := C.luaL_newstate()
C.lua_gc(vm, C.LUA_GCSTOP, 0)
C.luaL_openlibs(vm)
C.lua_gc(vm, C.LUA_GCRESTART, 0)
C.register_go_method(vm)
vmKey := generateLuaStateId(vm)
rw.Lock()
defer rw.Unlock()
luaStateCache[vmKey] = vm
return vmKey, vm
}
func createLuaThread(vm *C.struct_lua_State) (int64, *C.struct_lua_State) {
L := C.lua_newthread(vm)
vmKey := generateLuaStateId(L)
rw.Lock()
defer rw.Unlock()
luaStateCache[vmKey] = vm
return vmKey, L
}
func findLuaState(vmKey int64) (*C.struct_lua_State, error) {
rw.RLock()
defer rw.RUnlock()
target, ok := luaStateCache[vmKey]
if ok {
return target, nil
} else {
return nil, errors.New("Invalid Lua Vm Key")
}
}
func destoryLuaState(vmKey int64) {
rw.Lock()
defer rw.Unlock()
delete(luaStateCache, vmKey)
}