Skip to content

Instantly share code, notes, and snippets.

@ggzeng
Last active June 16, 2021 07:00
Show Gist options
  • Save ggzeng/6773666abd00b4ee46dad15753f5f36d to your computer and use it in GitHub Desktop.
Save ggzeng/6773666abd00b4ee46dad15753f5f36d to your computer and use it in GitHub Desktop.
在golang里调用lua函数
package main
import (
"fmt"
lua "github.com/yuin/gopher-lua"
)
func main() {
L := lua.NewState()
defer L.Close()
// 加载fib.lua
if err := L.DoFile("fib.lua"); err != nil {
panic(err)
}
// 调用fib(n)
err := L.CallByParam(lua.P{
Fn: L.GetGlobal("fib"), // 获取fib函数引用
NRet: 1, // 指定返回值数量
Protect: true, // 如果出现异常,是panic还是返回err
}, lua.LNumber(10)) // 传递输入参数n=10
if err != nil {
panic(err)
}
// 获取返回结果
ret := L.Get(-1)
// 从堆栈中扔掉返回结果
L.Pop()
// 打印结果
res, ok := ret.(lua.LNumber)
if ok {
fmt.Println(int(res))
} else {
fmt.Println("unexpected result")
}
}
function fib(n)
if n < 2 then
return 1
end
return fib(n-1) + fib(n-2)
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment