- 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)
- fmt.Println("Done!")
- }
来源: http://www.bubuko.com/infodetail-3040883.html