首頁  >  文章  >  後端開發  >  如何使用 gopher-lua 定義一個 Lua 函數,該函數有一個預先定義的表作為參數,Lua 腳本可以在該函數中存取該表?

如何使用 gopher-lua 定義一個 Lua 函數,該函數有一個預先定義的表作為參數,Lua 腳本可以在該函數中存取該表?

PHPz
PHPz轉載
2024-02-09 20:57:08889瀏覽

如何使用 gopher-lua 定义一个 Lua 函数,该函数有一个预定义的表作为参数,Lua 脚本可以在该函数中访问该表?

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程式碼範例:

<code>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)
}
</code>

sample.lua檔案:

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

    return 0
end
</code>

結果:

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

以上是如何使用 gopher-lua 定義一個 Lua 函數,該函數有一個預先定義的表作為參數,Lua 腳本可以在該函數中存取該表?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文轉載於:stackoverflow.com。如有侵權,請聯絡admin@php.cn刪除