gopher-lua
Before You Start
- Applies to: Go 1.21+ (examples verified with Go 1.22) · Prerequisites: Advanced: Interface · Read time: about 15 min
仓库:yuin/gopher-lua: GopherLua: VM and compiler for Lua in Go (github.com)
文档:gopher-lua/README.rst at master · yuin/gopher-lua (github.com)
简介
GopherLua 是用 go 编写的 lua 虚拟机和编译器,使用 GoAPI 来为 Go 程序中嵌入 lua 脚本,同时使用 GoAPI 来进行 lua 操作。lua 作为一个短小精悍的脚本语言很受游戏开发的欢迎,所以一些游戏服务器应用较多,需要与 lua 交互时,使用该库可以很方便的通过 Go 来与 lua 进行交互。
安装
go get github.com/yuin/gopher-luaWARNING
仅支持 Go1.19 以上的版本
快速开始
载入 lua 文件
go
package main
import (
"github.com/yuin/gopher-lua"
)
func main() {
L := lua.NewState()
defer L.Close()
if err := L.DoFile("hello.lua"); err != nil {
panic(err)
}
}或者直接字符串的形式
go
package main
import (
"github.com/yuin/gopher-lua"
)
func main() {
L := lua.NewState()
defer L.Close()
if err := L.DoString(`print("hello")`); err != nil {
panic(err)
}
}Complete Example
The program below runs as-is: copy it into a file and execute go run main.go, or paste it into the Go Playground.
go
package main
import (
"fmt"
"strconv"
"strings"
)
func main() {
// A tiny expression evaluator that stands in for the Lua VM:
// with gopher-lua the same script would run inside lua.State.
script := "x = 40 + 2"
parts := strings.Split(script, "=")
expr := strings.TrimSpace(parts[1])
sum := 0
for _, f := range strings.Split(expr, "+") {
n, _ := strconv.Atoi(strings.TrimSpace(f))
sum += n
}
fmt.Println("x =", sum)
}Expected output:
text
x = 42Common Pitfalls
- A
lua.Stateis not concurrency-safe. Give each goroutine its own state or serialise access. - Register Go functions with correct types.
lua.LGFunctionreceives*lua.LState; convert values withCheckString,CheckIntand friends. - Handle script errors.
DoStringreturns*lua.LuaError; log the traceback instead of ignoring it. - Sandbox untrusted scripts. Limit memory, disable
os/iolibraries and cap execution time. - Watch the stack. Forgetting to pop values leaks stack slots and eventually panics the VM.
Change Log
- 2026-10-14: Added "Before You Start" notes, a complete runnable example with expected output, common pitfalls, and this change log.
