package main import ( "doll/internal/log" "os" lua "github.com/yuin/gopher-lua" ) // square multiplies number by itself. func square(L *lua.LState) int { // get first (1) function argument and convert to int i := L.ToInt(1) // make calculation and cast to LNumber ln := lua.LNumber(i * i) // Push it to the stack L.Push(ln) // Notify that we pushed one value to the stack return 1 } func main() { // Init log subsystem. log.Init("info", os.Stderr) file := "example_data/03-test.lua" // Load the Lua script file. log.Infof("Loading %s", file) // We can execute script directly via L.DoFile("./example_data/03-test.lua") but in practice we'll get scripts as // strings - snippets from templates - so, testing/checking how it works is not use for project. luaCode, err := os.ReadFile(file) if err != nil { log.Fatalf("Error reading Lua file %s: %s", file, err) } log.Info("Creating new Lua state") L := lua.NewState() defer L.Close() log.Info("Registering go function as lua built-in function") L.SetGlobal("square", L.NewFunction(square)) log.Info("Evaluating Lua code") if err := L.DoString(string(luaCode)); err != nil { log.Errorf("Error evaluating Lua code: %s", err) os.Exit(1) } } /* vim: set ft=go noet ai ts=4 sw=4 sts=4: */