forked from kabukky/journey
-
Notifications
You must be signed in to change notification settings - Fork 0
/
luapool.go
67 lines (58 loc) · 1.39 KB
/
luapool.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
// +build !noplugins
package plugins
import (
"github.com/kabukky/journey/structure"
"github.com/yuin/gopher-lua"
"sync"
)
// Global LState pool
var LuaPool *lStatePool
type lStatePool struct {
m sync.Mutex
files map[string]string
saved []map[string]*lua.LState
}
func (pl *lStatePool) Get(helper *structure.Helper, values *structure.RequestData) map[string]*lua.LState {
pl.m.Lock()
defer pl.m.Unlock()
n := len(pl.saved)
if n == 0 {
x := pl.New()
// Since these are new lua states, do the lua file.
for key, value := range x {
setUpVm(value, helper, values, LuaPool.files[key])
value.DoFile(LuaPool.files[key])
}
return x
}
x := pl.saved[n-1]
// Set the new values for this request in every lua state
for key, value := range x {
setUpVm(value, helper, values, LuaPool.files[key])
}
pl.saved = pl.saved[0 : n-1]
return x
}
func (pl *lStatePool) New() map[string]*lua.LState {
stateMap := make(map[string]*lua.LState, 0)
for key, _ := range LuaPool.files {
L := lua.NewState()
stateMap[key] = L
}
return stateMap
}
func (pl *lStatePool) Put(L map[string]*lua.LState) {
pl.m.Lock()
defer pl.m.Unlock()
pl.saved = append(pl.saved, L)
}
func (pl *lStatePool) Shutdown() {
for _, stateMap := range pl.saved {
for _, value := range stateMap {
value.Close()
}
}
}
func newLuaPool() *lStatePool {
return &lStatePool{saved: make([]map[string]*lua.LState, 0, 4)}
}