package main
import (
"fmt"
"github.com/yuin/gopher-lua"
)
func hello(L *lua.LState) int {
inputparam := L.ToInt(1)
fmt.Println("func hello get:",inputparam)
//将返回参数压入栈中
L.Push(lua.LString("hello"))
//返回参数为1个
return 1
}
func main() {
L := lua.NewState()
defer L.Close()
//读写全局变量
L.SetGlobal("Age",lua.LNumber(8))
fmt.Println(L.GetGlobal("Age"))
//生成一个带名字的table
var t = L.NewTable()
t.RawSetString("ID",lua.LNumber(110))
t.RawSetString("Name",lua.LString("LULU"))
L.SetGlobal("stu_table",t)
//生成一个带名字的table2
if err := L.DoString(`
person = {
name = "Michel",
age = "31", -- weakly input
work_place = "San Jose",
role = {
{
name = "Administrator"
},
{
name = "Operator"
}
}
}
`); err != nil {
panic(err)
}
//生成一个带名字的table3
var t3 = L.NewTable()
L.SetTable(t3,lua.LString("Height"),lua.LNumber(1009))
L.SetGlobal("late",t3)
//读取table中的所有数据1
var r = L.GetGlobal("person")
fmt.Println(r.Type())
//读取table中的所有数据2
fmt.Println(L.GetTable(r,lua.LString("work_place")))
fmt.Println(L.GetTable(r,lua.LString("name")))
//读取table中的所有数据3
fmt.Println(L.GetField(r,"work_place"))
fmt.Println(L.GetField(r,"name"))
fmt.Println(L.Register)
////读取table中的所有数据4
fmt.Println(L.GetTable(t3,lua.LString("Height")))
//遍历读取table中的key,value
//待补充
//互相调用函数
//注册go函数
L.Register("hello",hello)
// 生成一个lua函数
err := L.DoString(`
function info(n)
ret = hello(n)
return ret
end`)
if err != nil{
panic(err)
}
fn := L.GetGlobal("info")
if err := L.CallByParam(lua.P{
Fn: fn,
NRet: 1,
Protect: true,
}, lua.LNumber(10)); err != nil {
panic(err)
}
//这里获取函数返回值
ret := L.Get(-1)
fmt.Println(ret)
//从lua文件中读取lua字符串
err = L.DoFile("./test.lua")
if err != nil{
fmt.Println("err",err.Error())
panic(err)
}
fmt.Println(L.GetGlobal("title"))
title := L.GetGlobal("title")
fmt.Println(reflect.TypeOf(title))
fmt.Println(title)
fmt.Println("Done!")
}