A step-by-step tutorial for implementing and using the Glazed Lua wrapper in your applications
This tutorial will guide you through the process of integrating and using the Glazed Lua wrapper in your applications. We'll create a simple animal list command and execute it from Lua.
github.com/yuin/gopher-lua package installedFirst, we need to create a new Lua state that will serve as our execution environment:
L := lua.NewState()
defer L.Close()
Make sure to always close the Lua state when you're done to prevent memory leaks.
Let's create a simple command that we'll use throughout this tutorial. We'll implement an AnimalListCommand that returns information about different animals:
type AnimalListCommand struct {
// Command implementation
}
func NewAnimalListCommand() (*AnimalListCommand, error) {
// Command initialization
return &AnimalListCommand{}, nil
}
Now we'll register our Glazed command with the Lua state:
animalListCmd, _ := NewAnimalListCommand()
lua2.RegisterGlazedCommand(L, animalListCmd)
This registration process:
animal_list_params)Let's create a Lua script that uses our registered command. This script will:
local params = {
default = {
count = 3
},
glazed = {
fields = {"animal", "diet"}
}
}
-- Execute the command
local result = animal_list(params)
-- Print results
for i, row in ipairs(result) do
print(string.format("Animal %d: %s, Diet: %s", i, row.animal, row.diet))
end
-- Print field information
print("\nFields for animal_list command:")
for section_name, section_fields in pairs(animal_list_params) do
print("Section: " .. section_name)
for field_name, field_info in pairs(section_fields) do
print(string.format(" %s (%s): %s",
field_name,
field_info.type,
field_info.description))
print(string.format(" Default: %s",
tostring(field_info.default)))
print(string.format(" Required: %s",
tostring(field_info.required)))
end
end
Execute the Lua script in your Go application:
if err := L.DoString(script); err != nil {
fmt.Printf("Error executing Lua script: %v\n", err)
}
For more complex commands, you might need to work with nested field structures. Here's how to use nested tables:
local params = {
default = {
count = 3
},
glazed = {
fields = {"animal", "diet"},
format = "table"
},
output = {
file = "animals.txt"
}
}
local result = animal_list(params)
In Go, handle these nested tables using the ParseNestedLuaTableMiddleware:
middlewares_ := []middlewares.Middleware{
lua2.ParseNestedLuaTableMiddleware(L, luaTable),
sources.FromDefaults(sources.WithSource("defaults")),
}
err := sources.Execute(cmd.Description().Sections,
parsedSections,
middlewares_...)
This tutorial covered the basics of implementing the Glazed Lua wrapper in your applications. You learned how to:
For more detailed information about specific features and advanced usage, refer to the main Glazed Lua Wrapper documentation using glaze help lua.