package luaInGo
|
|
|
|
import (
|
|
lua "github.com/yuin/gopher-lua"
|
|
"strings"
|
|
"sync"
|
|
)
|
|
|
|
type lStatePool struct {
|
|
m sync.Mutex
|
|
saved []*lua.LState
|
|
}
|
|
|
|
// Get 从池中取出一个LState,若池中没有,则新增一个
|
|
func (pl *lStatePool) Get() *lua.LState {
|
|
pl.m.Lock()
|
|
defer pl.m.Unlock()
|
|
n := len(pl.saved)
|
|
if n == 0 {
|
|
return pl.New()
|
|
}
|
|
x := pl.saved[n-1]
|
|
pl.saved = pl.saved[0 : n-1]
|
|
return x
|
|
}
|
|
|
|
// Put 用完LState后放回池中
|
|
func (pl *lStatePool) Put(L *lua.LState) {
|
|
pl.m.Lock()
|
|
defer pl.m.Unlock()
|
|
if len(pl.saved) > NaxPoolSize {
|
|
L.Close()
|
|
} else {
|
|
// 放回的时候 清理一下 堆栈 确认数据正常
|
|
L.SetTop(0)
|
|
pl.saved = append(pl.saved, L)
|
|
}
|
|
}
|
|
|
|
func (pl *lStatePool) ShutDown() {
|
|
for _, L := range pl.saved {
|
|
L.Close()
|
|
}
|
|
}
|
|
|
|
func (pl *lStatePool) New() *lua.LState {
|
|
L := lua.NewState()
|
|
|
|
//提供全局函数给lua
|
|
PreLoadGo(L)
|
|
|
|
//加载go提供元表给lua
|
|
// golua.RegisterPersonType(L)
|
|
|
|
// 添加lua脚本自动搜索路径
|
|
// Tamper package.path according to configuration...
|
|
t := L.GetGlobal("package").(*lua.LTable)
|
|
// Get "path" from package table
|
|
lPath := lua.LString("path")
|
|
s := L.RawGet(t, lPath).(lua.LString).String()
|
|
|
|
// Create list of elements to join for new package path
|
|
elems := []string{s}
|
|
elems = append(elems, "./luaScript/?.lua")
|
|
|
|
// Set new package.path
|
|
L.RawSet(t, lPath, lua.LString(strings.Join(elems, ";")))
|
|
|
|
//加载lua脚本 仅仅加载入口函数模块的lua
|
|
if err := L.DoFile("./luaScript/main.lua"); err != nil {
|
|
println("load the main lua files error")
|
|
panic(err)
|
|
}
|
|
|
|
return L
|
|
}
|