Documentation
¶
Overview ¶
Package lua embeds a Lua runtime for hex applications using github.com/yuin/gopher-lua.
hex/lua is intentionally minimal (ADR-0007): it exposes an Environment that compiles and executes Lua scripts and gives consumers access to the underlying *lua.LState so they can install whatever Go→Lua bindings they need. hex ships no modules, no plugin system, no discovery convention. Those live in consumer apps.
Compilation is separated from execution so scripts can be compiled once and run many times against many environments — the typical pattern for load testing (see zk/lemming) or plugin dispatch.
Example:
env := lua.New()
defer env.Close()
// Install a consumer-owned Go→Lua binding.
env.PreloadModule("http", myhttp.Loader)
// Set a global.
if err := env.SetGlobal("build_version", "v1.2.3"); err != nil {
return err
}
// Compile once, execute many times.
script, err := env.Compile("print(build_version)", "hello.lua")
if err != nil { return err }
if err := env.Exec(script); err != nil { return err }
The zero value is not usable; call New.
Index ¶
- type Environment
- func (e *Environment) CheckFile(path string) error
- func (e *Environment) CheckString(source, name string, lang Language) error
- func (e *Environment) Close() error
- func (e *Environment) Exec(script *Script) error
- func (e *Environment) ExecFile(path string) error
- func (e *Environment) ExecString(source, name string) error
- func (e *Environment) GetGlobal(name string) lua.LValue
- func (e *Environment) LoadFile(path string) (*Script, error)
- func (e *Environment) LoadString(source, name string, lang Language) (*Script, error)
- func (e *Environment) PreloadModule(name string, loader lua.LGFunction)
- func (e *Environment) SetGlobal(name string, value any) error
- func (e *Environment) SetStdout(w io.Writer)
- func (e *Environment) SetType(moduleName, tealSource string)
- func (e *Environment) Stdout() io.Writer
- func (e *Environment) Types() map[string]string
- type Language
- type Option
- type Script
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
This section is empty.
Types ¶
type Environment ¶
type Environment struct {
// L is the underlying gopher-lua state. Exported so consumers can
// install modules, register types, and perform advanced operations
// that hex/lua does not wrap. Callers should treat direct L access as
// an escape hatch, not the primary API.
L *lua.LState
// contains filtered or unexported fields
}
Environment is a single Lua VM with hex-friendly lifecycle helpers.
func New ¶
func New(opts ...Option) *Environment
New returns a fresh Environment. Options tune the VM; the zero-argument call is safe and produces a Lua state with stdlib loaded.
func (*Environment) CheckFile ¶
func (e *Environment) CheckFile(path string) error
CheckFile runs a file through validation without executing it. .lua parses only. .tl runs the Teal type-checker. .fnl runs the Fennel compiler as a syntax check.
Intended for CI (fail the build on typecheck errors) and for pre-flight validation of user-supplied scripts.
func (*Environment) CheckString ¶
func (e *Environment) CheckString(source, name string, lang Language) error
CheckString validates source without executing it. Teal runs the full typechecker. Fennel and Lua run through their parsers (Fennel has no static type layer).
func (*Environment) Close ¶
func (e *Environment) Close() error
Close releases the Lua state's resources. Safe to call more than once. After Close, the Environment must not be used.
func (*Environment) Exec ¶
func (e *Environment) Exec(script *Script) error
Exec runs a compiled script against the environment. Any Lua panic is converted into an error with the stack trace attached.
func (*Environment) ExecFile ¶
func (e *Environment) ExecFile(path string) error
ExecFile compiles and executes a Lua or Teal file. .tl files are transpiled through the embedded Teal compiler (see hex/lua/teal) before being handed to gopher-lua. Teal support is lazily loaded on the first .tl encountered per Environment, so pure-Lua users pay nothing.
func (*Environment) ExecString ¶
func (e *Environment) ExecString(source, name string) error
ExecString compiles source once and executes it. For scripts that will run many times, prefer Compile + Exec to skip the parse phase.
func (*Environment) GetGlobal ¶
func (e *Environment) GetGlobal(name string) lua.LValue
GetGlobal returns the Lua value at name. If the global is unset, the result is lua.LNil.
func (*Environment) LoadFile ¶
func (e *Environment) LoadFile(path string) (*Script, error)
LoadFile reads path and compiles it to a Script, auto-detecting the language via file extension: .tl → Teal, .fnl → Fennel, anything else → Lua.
func (*Environment) LoadString ¶
func (e *Environment) LoadString(source, name string, lang Language) (*Script, error)
LoadString compiles source (named for error messages) as the specified Language and returns a runnable Script. Teal and Fennel route through their respective embedded compilers first; the resulting Lua is parsed by gopher-lua.
func (*Environment) PreloadModule ¶
func (e *Environment) PreloadModule(name string, loader lua.LGFunction)
PreloadModule registers a module loader under name. When a Lua script calls `require("name")`, loader is invoked to push the module table onto the stack. Matches gopher-lua's L.PreloadModule but hides that detail so consumers do not need to type-assert.
func (*Environment) SetGlobal ¶
func (e *Environment) SetGlobal(name string, value any) error
SetGlobal installs value as a Lua global. Supported Go types: string, bool, int/int64/uint64, float64, nil, and any lua.LValue. Unsupported types return an error.
func (*Environment) SetStdout ¶
func (e *Environment) SetStdout(w io.Writer)
SetStdout redirects the Lua `print` function's output. The change is live: subsequent print() calls write to w. Nil restores os.Stdout.
func (*Environment) SetType ¶
func (e *Environment) SetType(moduleName, tealSource string)
SetType registers a Teal .d.tl source describing the shape of a module. hex/lua/teal.Session reads these at session init and exposes them via package.path so require("name") typechecks in Teal source.
This is compile-time metadata only — it has no effect on the runtime module (registered via PreloadModule) and is silently ignored when running Lua directly (Lua doesn't typecheck).
func (*Environment) Stdout ¶
func (e *Environment) Stdout() io.Writer
Stdout returns the current writer that print() flushes to.
func (*Environment) Types ¶
func (e *Environment) Types() map[string]string
Types returns a copy of the registered type stubs. Consumers who want the underlying map (to mutate) should use SetType.
type Language ¶
type Language int
Language selects which compiler front-end LoadString / CheckString / LoadFile route the source through.
const ( // Lua is plain gopher-lua source. No compilation step. Lua Language = iota // Teal is the typed Lua dialect. Source goes through the // embedded Teal compiler; type errors surface at load time. Teal // Fennel is the Lisp dialect that compiles to Lua. Source // goes through the embedded Fennel compiler; only surface // errors (unbalanced parens, etc.) surface at load time — // Fennel has no static type-checker. Fennel )
func LanguageFor ¶
LanguageFor returns the Language implied by the given file extension. Unknown extensions default to Lua.
type Option ¶
type Option func(*envConfig)
Option configures a new Environment.
func WithCallStackSize ¶
WithCallStackSize sets the maximum Lua call-stack depth. Default is gopher-lua's default (~256). Increase for deeply recursive scripts.
func WithPackagePath ¶
WithPackagePath appends directories to Lua's `package.path` so scripts can `require("x")` files under those directories. Directories are searched in the order given, before Lua's default paths.
func WithRegistrySize ¶
WithRegistrySize sets the initial size of the Lua registry. Default is gopher-lua's default. Tune if you know you will register many values.
func WithoutStandardLibraries ¶
func WithoutStandardLibraries() Option
WithoutStandardLibraries opens the Environment without gopher-lua's default stdlib (io, os, debug, etc). Use for locked-down sandboxes.
type Script ¶
type Script struct {
// contains filtered or unexported fields
}
Script is a compiled Lua chunk that can be executed against any Environment. The same Script is safe to share across environments (each Exec re-attaches it) but not safe for concurrent Exec calls on the same Environment; use one Environment per goroutine.
func Compile ¶
Compile parses source into a Script. name is used in error messages and Lua stack traces; pass the file path or a synthetic name like "inline". Compile does not touch the Environment; you can compile once and share the Script across many environments.
func CompileFile ¶
CompileFile reads path and compiles its contents. The file's absolute path is used as the script name.
Directories
¶
| Path | Synopsis |
|---|---|
|
Package fennel makes .fnl (Fennel) source files runnable through gopher-lua by embedding the Fennel compiler (a self-contained Lua source file distributed by the Fennel project).
|
Package fennel makes .fnl (Fennel) source files runnable through gopher-lua by embedding the Fennel compiler (a self-contained Lua source file distributed by the Fennel project). |
|
Package plugin discovers repo-local Cobra commands written in Lua, Teal, or Fennel and merges them into an existing command tree.
|
Package plugin discovers repo-local Cobra commands written in Lua, Teal, or Fennel and merges them into an existing command tree. |
|
Package provider is the default hex/lua service provider.
|
Package provider is the default hex/lua service provider. |
|
Package repl provides an interactive Read-Eval-Print Loop for Teal and Lua sources, wired to a caller-provided *lua.Environment.
|
Package repl provides an interactive Read-Eval-Print Loop for Teal and Lua sources, wired to a caller-provided *lua.Environment. |
|
Package teal makes .tl (Teal) source files runnable through gopher-lua by embedding the Teal compiler + Lua 5.2 compatibility shims.
|
Package teal makes .tl (Teal) source files runnable through gopher-lua by embedding the Teal compiler + Lua 5.2 compatibility shims. |