#Embedding Lua Scripts in Go with Shopify/go-lua

Elliot Forbes Elliot Forbes · Dec 17, 2022 · 1 min read

Welcome Gophers! In this tutorial, we are going to be taking a look at how we can embed Lua scripts in our Go applications.

Getting Started

You can use the Shopify/go-lua package to embed Lua in Go. Here’s an example of how to do it:

package main

import (
	"fmt"

	"github.com/Shopify/go-lua"
)


func main() {
	// Create a new Lua state
	l := lua.NewState()
	defer l.Close()

	// Load the standard libraries
	lua.OpenLibraries(l)

	// Load and run a Lua script
	if err := lua.DoFile(l, "script.lua"); err != nil {
		fmt.Println(err)
		return
	}
}

This example loads and runs a Lua script called “script.lua”. You can also execute Lua code directly by using the DoString function:

if err := lua.DoString(l, "print('Hello from Lua')"); err != nil {
	fmt.Println(err)
	return
}

Conclusion

Embedding Lua in Go provides a powerful way to add scripting capabilities to your applications. The Shopify/go-lua package makes it straightforward to integrate Lua scripts while maintaining the performance benefits of compiled Go code. For more advanced patterns, check out the Go interfaces article to understand how to design extensible systems.