php小編小新將為你介紹如何使用gopher-lua在Lua函數中定義一個帶有預定義表參數的函數,并且在函數內部訪問該表。gopher-lua是一個Go語言實現的Lua解釋器,可以在Go程序中嵌入和執行Lua腳本。通過合理的代碼設計和使用,我們可以輕松實現這一目標。接下來,我們將詳細講解如何做到這一點。
問題內容
我知道如何定義 Go 函數并將其設置為全局(文檔中的 Double 示例)。但是,如果這個函數的參數應該是一個預定義的表呢?
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(…)),但如何將其添加到預期函數中?
在 Go 中添加一些函數
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 中工作。
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
登錄后復制