我知道如何定义GO函数并将其设置为全局函数(文档中的两个示例).但是,如果该函数的参数应该是预定义的表,该怎么办呢?

function calling_this_function_would_be_required(predefined_table)
  print(predefined_table["something"])
end

IMAP服务器Dovecot确实提供了类似上面的内容:https://doc.dovecot.org/configuration_manual/authentication/lua_based_authentication/#examples

我还想为预定义的函数提供一个表(甚至是用户数据).但我真的不知道如何实现这一点.

设置一个全局表很容易(L.SetGlobal(...)),但如何将其添加到预期的函数中?

在围棋中添加一些功能

func CallMe(L *lua.LState) {
    // How do I add a table as argument??
}

func Foo() {
    L := NewState()
    defer L.Close()

    t := L.NewTable()
    t.RawSetString("example", lua.LString("some_value"))

    // I do not want a global table. I would like an expected Lua function that has _this_ table as argument
    L.SetGlobal("predefined_table", t)

    // Not even sure with his...
    L.SetGlobal("calling_this_function_is_required", L.NewFunction©llMe)) 
}

如果有人能照亮我一点那就太好了:-)提前谢谢

推荐答案

基于@Koyaanisqatsi的回答,我发现了如何在围棋中让事情运转起来.

GO代码示例:

package main

import (
    "fmt"

    "github.com/yuin/gopher-lua"
)

type Person struct {
    Name       string
    GivenName  string
    Street     string
    PostalCode string
    City       string
}

func main() {
    p := &Person{
        Name:       "Mustermann",
        GivenName:  "Max",
        Street:     "Sackgasse 19",
        PostalCode: "36304",
        City:       "Alsfeld",
    }

    L := lua.NewState()
    defer L.Close()

    if err := L.DoFile("sample.lua"); err != nil {
        panic(err)
    }

    t := L.NewTable()
    t.RawSetString("name", lua.LString(p.Name))
    t.RawSetString("given_name", lua.LString(p.GivenName))
    t.RawSetString("street", lua.LString(p.Street))
    t.RawSetString("postal_code", lua.LString(p.PostalCode))
    t.RawSetString("city", lua.LString(p.City))

    if err := L.CallByParam(lua.P{
        Fn:      L.GetGlobal("call_me"),
        NRet:    1,
        Protect: true,
    }, t); err != nil {
        panic(err)
    }

    ret := L.Get(-1) // returned value
    L.Pop(1)         // remove received value

    fmt.Println("The result of the Lua function is:", ret)
}

Sample.lua文件:

function call_me(tbl)
    print(tbl.name)
    print(tbl.given_name)
    print(tbl.street)
    print(tbl.postal_code)
    print(tbl.city)

    return 0
end

结果:

Mustermann
Max
Sackgasse 19
36304
Alsfeld
The result of the Lua function is: 0

Go相关问答推荐

在保留额外参数的同时解封YAML

如何描述OpenAPI规范中围棋的数据类型.JSON?

为什么(编码器).EncodeElement忽略";,innerxml";标记?

如果values.yaml文件中不存在某个属性,如何返回默认的FALSE?

从MySQL/GO表获取行数据

什么东西逃到了堆里?

为什么 net/http 不遵守超过 30 秒的超时持续时间?

Apache Beam 在 Go 中从 PCollection 中 Select 前 N 行

也许在 golang 中包(字符串和字符串类型不匹配)

Go http.FileServer 给出意外的 404 错误

Go 信号处理程序不处理终端窗口关闭

panic :拨号 tcp:在 172.22.64.1:53 上查找 bookstoreDB:没有这样的主机

无限期运行 Go routine (完成后重新启动)

Go:用于 XML 解码的嵌套 struct 中的提升字段

如何在golang中使用ozzo验证进行时间最大验证

HCL 解码:具有多个标签的块

Go模板中的浮点除法

为什么 Go 中的 maps.Keys() 将 map 类型指定为 M?

Golang 'defer' 导致发送(接收)API 响应延迟

如何获得Ent中数字列的总和