前言
gopher-lua中也有c++中的lua.next
函数,不过目前我没有查到gopher-lua的next函数用法,因此这里用的是func (ls *LState) ForEach(tb *LTable, cb func(LValue, LValue))
这个函数。
代码
在这里,我们从lua文件中取一个"mytable"的table结构,并且把其中元素存储到map[string]string中
Lua代码:
mytable = {}
mytable["key1"] = "value1"
mytable["key2"] = "value2"
mytable["key3"] = "value3"
这里我们展示下ForEach
函数怎么用
package main
import (
"github.com/golang/glog"
"github.com/yuin/gopher-lua"
)
type LuaMatcher struct{
LuaState *lua.LState
}
func NewLuaMatcher() *LuaMatcher{
return &LuaMatcher{
LuaState: nil,
}
}
func (L *LuaMatcher)Init(path string) bool{
L.LuaState = lua.NewState()
err := L.LuaState.DoFile(path)
if err != nil{
glog.Error("lua init fail")
return false
}
return true
}
func (L *LuaMatcher) PrintKeyValue(L1 lua.LValue, L2 lua.LValue){
if lv, ok := L2.(*lua.LTable); ok{
lv.ForEach(L.GetResult) //递归调用ForEach函数
} else {
fmt.Println("k = ", L1). //注意这里是函数传进来的参数
fmt.Println("v = ", L2)
}
}
int main(){
L := new(LuaMatcher)
L.Init("mylua.lua") // path是你存放lua文件的路径
Table := L.L.GetGlobal("mytable") //获取table
L.L.Push(Table)
t := L.L.CheckTable(-1)
t.ForEach(L.PrintKeyValue)//遍历打印
}
结果:
key2 value2
key3 value3
key1 value1