Documentation ¶
Overview ¶
Package lua implements a Lua 5.4 virtual machine. It is similar to the de facto C Lua implementation, but takes advantage of the Go runtime and garbage collector.
State is the main entrypoint for this package, and OpenLibraries is used to load the standard library.
Relation to the C API ¶
Methods on State are generally equivalent to C functions that start with “lua_” (the Lua C API); functions in this package are generally equivalent to C functions that start with “luaL_” (the auxiliary library).
However, there are some differences:
- Error handling is handled using the standard Go error type. This is documented in more depth on *State.Call, but importantly, note that *State.Call and other functions that can call Lua code will generally not push an error object on the stack.
- This package does not provide to-be-closed slots to functions implemented in Go. It is assumed that such functions will use “defer” to handle cleanup. This eliminates the need to check for errors in functions like *State.Pop.
- Coroutines are not implemented. Maybe one day.
- There is no light userdata, despite there being a TypeLightUserdata constant. Full userdata holds an “any” value, which is more flexible in Go.
- There is no lua_topointer, but you can use *State.ID for similar purposes.
- State does not have to be closed: the Go garbage collector fully manages its resources.
- The “lua_getinfo” interface is simplified: *State.Info only takes a level and fills all fields. *State.FunctionForLevel takes the place of calling “lua_getinfo” with the ‘f’ option.
Differences from de facto C implementation ¶
- The “__gc” (finalizer) metamethod is never called. Use “__close” instead, as the semantics are well-defined.
- Weak tables (i.e. the “__mode” metafield) are not supported.
- The “string” library has differences; see OpenString for more details.
Example ¶
package main import ( "context" "log" "strings" lua "zb.256lights.llc/pkg/internal/lua" ) func main() { ctx := context.Background() // Create an execution environment // and make the standard libraries available. state := new(lua.State) defer state.Close() if err := lua.OpenLibraries(ctx, state); err != nil { log.Fatal(err) } // Load Lua code as a chunk/function. // Calling this function then executes it. const luaSource = `print("Hello, World!")` if err := state.Load(strings.NewReader(luaSource), luaSource, "t"); err != nil { log.Fatal(err) } if err := state.Call(ctx, 0, 0, 0); err != nil { log.Fatal(err) } }
Output: Hello, World!
Index ¶
- Constants
- func CallMeta(ctx context.Context, l *State, obj int, event string) (bool, error)
- func CheckInteger(l *State, arg int) (int64, error)
- func CheckNumber(l *State, arg int) (float64, error)
- func CheckString(l *State, arg int) (string, error)
- func CheckUserdata(l *State, arg int, tname string) (any, error)
- func Len(ctx context.Context, l *State, idx int) (int64, error)
- func NewArgError(l *State, arg int, msg string) error
- func NewLib(l *State, reg map[string]Function)
- func NewMetatable(l *State, tname string) bool
- func NewTypeError(l *State, arg int, tname string) error
- func OpenLibraries(ctx context.Context, l *State) error
- func OpenString(ctx context.Context, l *State) (int, error)
- func OpenTable(ctx context.Context, l *State) (int, error)
- func Require(ctx context.Context, l *State, modName string, global bool, openf Function) error
- func SetFuncs(ctx context.Context, l *State, nUp int, reg map[string]Function) error
- func SetMetatable(l *State, tname string)
- func Subtable(ctx context.Context, l *State, idx int, fname string) (bool, error)
- func TestUserdata(l *State, idx int, tname string) (_ any, isUserdata bool)
- func ToConstant(l *State, idx int) (_ luacode.Value, ok bool)
- func ToString(ctx context.Context, l *State, idx int) (string, sets.Set[string], error)
- func Traceback(l *State, msg string, level int) string
- func UpvalueIndex(i int) int
- func Where(l *State, level int) string
- type BaseOptions
- type ComparisonOperator
- type Debug
- type Function
- type RandomSeed
- type RandomSource
- type Source
- type State
- func (l *State) AbsIndex(idx int) int
- func (l *State) Arithmetic(ctx context.Context, op luacode.ArithmeticOperator) error
- func (l *State) Call(ctx context.Context, nArgs, nResults, msgHandler int) error
- func (l *State) CheckStack(n int) bool
- func (l *State) Close() error
- func (l *State) Compare(ctx context.Context, idx1, idx2 int, op ComparisonOperator) (bool, error)
- func (l *State) Concat(ctx context.Context, n int) error
- func (l *State) Copy(fromIdx, toIdx int)
- func (l *State) CreateTable(nArr, nRec int)
- func (l *State) Dump(stripDebug bool) ([]byte, error)
- func (l *State) Field(ctx context.Context, idx int, k string) (Type, error)
- func (l *State) FunctionForLevel(level int) bool
- func (l *State) Global(ctx context.Context, name string) (Type, error)
- func (l *State) ID(idx int) uint64
- func (l *State) Index(ctx context.Context, idx int, i int64) (Type, error)
- func (l *State) Info(level int) *Debug
- func (l *State) Insert(idx int)
- func (l *State) IsBoolean(idx int) bool
- func (l *State) IsFunction(idx int) bool
- func (l *State) IsGoFunction(idx int) bool
- func (l *State) IsInteger(idx int) bool
- func (l *State) IsNil(idx int) bool
- func (l *State) IsNone(idx int) bool
- func (l *State) IsNoneOrNil(idx int) bool
- func (l *State) IsNumber(idx int) bool
- func (l *State) IsString(idx int) bool
- func (l *State) IsTable(idx int) bool
- func (l *State) IsUserdata(idx int) bool
- func (l *State) Len(ctx context.Context, idx int) error
- func (l *State) Load(r io.ByteScanner, chunkName Source, mode string) (err error)
- func (l *State) Metatable(idx int) bool
- func (l *State) NewUserdata(x any, numUserValues int)
- func (l *State) Next(idx int) bool
- func (l *State) Pop(n int)
- func (l *State) PushBoolean(b bool)
- func (l *State) PushClosure(n int, f Function)
- func (l *State) PushInteger(i int64)
- func (l *State) PushNil()
- func (l *State) PushNumber(n float64)
- func (l *State) PushString(s string)
- func (l *State) PushStringContext(s string, context sets.Set[string])
- func (l *State) PushValue(idx int)
- func (l *State) RawEqual(idx1, idx2 int) bool
- func (l *State) RawField(idx int, k string) Type
- func (l *State) RawGet(idx int) Type
- func (l *State) RawIndex(idx int, n int64) Type
- func (l *State) RawLen(idx int) uint64
- func (l *State) RawSet(idx int) error
- func (l *State) RawSetField(idx int, k string)
- func (l *State) RawSetIndex(idx int, n int64)
- func (l *State) Remove(idx int)
- func (l *State) Replace(idx int)
- func (l *State) Rotate(idx, n int)
- func (l *State) SetField(ctx context.Context, idx int, k string) error
- func (l *State) SetGlobal(ctx context.Context, name string) error
- func (l *State) SetIndex(ctx context.Context, idx int, i int64) error
- func (l *State) SetMetatable(idx int)
- func (l *State) SetTable(ctx context.Context, idx int) error
- func (l *State) SetTop(idx int)
- func (l *State) SetUpvalue(funcIndex int, i int) (upvalueName string, ok bool)
- func (l *State) SetUserValue(idx int, n int) bool
- func (l *State) StringContext(idx int) sets.Set[string]
- func (l *State) Table(ctx context.Context, idx int) (Type, error)
- func (l *State) ToBoolean(idx int) bool
- func (l *State) ToInteger(idx int) (n int64, ok bool)
- func (l *State) ToNumber(idx int) (n float64, ok bool)
- func (l *State) ToString(idx int) (s string, ok bool)
- func (l *State) ToUserdata(idx int) (_ any, isUserdata bool)
- func (l *State) Top() int
- func (l *State) Type(idx int) Type
- func (l *State) Upvalue(funcIndex int, i int) (upvalueName string, ok bool)
- func (l *State) UserValue(idx int, n int) Type
- type Type
- type WarnFunc
- type Warner
Examples ¶
Constants ¶
const ( VersionNum = 504 VersionMajor = 5 VersionMinor = 4 )
Version numbers.
const GName = "_G"
GName is the name of the global table.
const LoadedTable = "_LOADED"
LoadedTable is the key in the registry for table of loaded modules.
const MathLibraryName = "math"
MathLibraryName is the conventional identifier for the math library.
const MultipleReturns = luacode.MultiReturn
MultipleReturns is the sentinel that indicates that an arbitrary number of result values are accepted.
const RegistryIndex int = -maxStack - 1000
RegistryIndex is a pseudo-index to the registry, a predefined table that can be used by any Go code to store whatever Lua values it needs to store.
const (
RegistryIndexGlobals int64 = 2
)
Predefined values in the registry.
const StringLibraryName = "string"
StringLibraryName is the conventional identifier for the string manipulation library.
const TableLibraryName = "table"
TableLibraryName is the conventional identifier for the table manipulation library.
const UnknownSource = luacode.UnknownSource
UnknownSource is a placeholder for an unknown Source.
const Version = "Lua 5.4"
Version is the version string without the final "release" number.
Variables ¶
This section is empty.
Functions ¶
func CallMeta ¶
CallMeta calls a metamethod.
If the object at index obj has a metatable and this metatable has a field event, this function calls this field passing the object as its only argument. In this case this function returns true and pushes onto the stack the value returned by the call. If an error is raised during the call, CallMeta returns an error without pushing any value on the stack. If there is no metatable or no metamethod, this function returns false without pushing any value on the stack.
func CheckInteger ¶
CheckInteger checks whether the function argument arg is an integer (or can be converted to an integer) and returns this integer.
func CheckNumber ¶
CheckNumber checks whether the function argument arg is a number and returns this number.
func CheckString ¶
CheckString checks whether the function argument arg is a string and returns this string. This function uses State.ToString to get its result, so all conversions and caveats of that function apply here.
func CheckUserdata ¶
CheckUserdata returns a copy of the Go value for the given userdata argument. CheckUserdata returns an error if the function argument arg is not a userdata of the type tname (see NewMetatable).
func NewArgError ¶
NewArgError returns a new error reporting a problem with argument arg of the Go function that called it, using a standard message that includes msg as a comment.
func NewMetatable ¶
NewMetatable gets or creates a table in the registry to be used as a metatable for userdata. If the table is created, adds the pair __name = tname, and returns true. Regardless, the function pushes onto the stack the final value associated with tname in the registry.
func NewTypeError ¶
NewTypeError returns a new type error for the argument arg of the Go function that called it, using a standard message; tname is a "name" for the expected type.
func OpenLibraries ¶
OpenLibraries opens all standard Lua libraries into the given state with their default settings.
func OpenString ¶
OpenString is a Function that loads the string manipulation library. This function is intended to be used as an argument to Require.
Differences from de facto C implementation ¶
- Patterns do not support backreferences (i.e. %0 - %9), balances (i.e. %b), or frontiers (%f). Attempting to use any of these pattern items will raise an error.
- Character sets with classes in ranges (e.g. [%a-z]) raise an error instead of silently exhibiting undefined behavior.
func OpenTable ¶
OpenTable is a Function that loads the table manipulation library. This function is intended to be used as an argument to Require.
func Require ¶
Require loads a module using the given openf function. If package.loaded[modName] is not true, Require calls the function with the string modName as an argument and sets the call result to package.loaded[modName], as if that function has been called through require. If global is true, also stores the module into the global modName. Leaves a copy of the module on the stack.
func SetFuncs ¶
SetFuncs registers all functions the map reg into the table on the top of the stack (below optional upvalues, see next). Any nils are registered as false.
When nUp is not zero, all functions are created with nup upvalues, initialized with copies of the nUp values previously pushed on the stack on top of the library table. These values are popped from the stack after the registration.
func SetMetatable ¶
SetMetatable sets the metatable of the object on the top of the stack as the metatable associated with name tname in the registry. NewMetatable can be used to create such a metatable.
func Subtable ¶
Subtable ensures that the value t[fname], where t is the value at index idx, is a table, and pushes that table onto the stack. Returns true if it finds a previous table there and false if it creates a new table.
func TestUserdata ¶
TestUserdata returns a copy of the Go value for the userdata at the given index. isUserdata is true if and only if the value at the given index is a userdata and has the type tname (see NewMetatable).
func ToConstant ¶
ToConstant converts the nil, boolean, number, or string at the given index to a luacode.Value.
func ToString ¶
ToString converts any Lua value at the given index to a Go string in a reasonable format.
If the value has a metatable with a __tostring field, then ToString calls the corresponding metamethod with the value as argument, and uses the result of the call as its result.
func Traceback ¶
Traceback creates a traceback of the call stack starting at the given level. Level 0 is the current running function, whereas level n+1 is the function that has called level n (except for tail calls, which do not count in the stack). msg is prepended to the traceback.
func UpvalueIndex ¶
UpvalueIndex returns the pseudo-index that represents the i-th upvalue of the running function. If i is outside the range [1, 256], UpvalueIndex panics.
func Where ¶
Where returns a string identifying the current position of the control at the given level in the call stack. Typically this string has the following format (including a trailing space):
chunkname:currentline:
Level 0 is the running function, level 1 is the function that called the running function, etc.
This function is used to build a prefix for error messages.
Types ¶
type BaseOptions ¶
type BaseOptions struct { // The “print” function will write to Output (or [os.Stdout] if nil). Output io.Writer // Warner handles calls to the “warn” function. Warner Warner // If LoadFile is not nil, // then the “loadfile” function will be replaced by the given implementation // and the “dofile” function will use it to load files. LoadFile Function }
BaseOptions is the parameter type for NewOpenBase.
type ComparisonOperator ¶
type ComparisonOperator int
ComparisonOperator is an enumeration of operators that can be used with *State.Compare.
const ( Equal ComparisonOperator = iota // == Less // < LessOrEqual // <= )
Defined ComparisonOperator values.
func (ComparisonOperator) String ¶
func (i ComparisonOperator) String() string
type Debug ¶
type Debug struct { // Name is a reasonable name for the given function. // Because functions in Lua are first-class values, they do not have a fixed name: // some functions can be the value of multiple global variables, // while others can be stored only in a table field. // The [*State.Info] function checks how the function was called to find a suitable name. // If they cannot find a name, then Name is set to the empty string. Name string // NameWhat explains the Name field. // The value of NameWhat can be // "global", "local", "method", "field", "upvalue", or the empty string, // according to how the function was called. // (Lua uses the empty string when no other option seems to apply.) NameWhat string // What is the string "Lua" if the function is a Lua function, // "Go" if it is a Go function, // "main" if it is the main part of a chunk. What string // Source is the source of the chunk that created the function. Source Source // CurrentLine is the current line where the given function is executing. // When no line information is available, CurrentLine is set to -1. CurrentLine int // LineDefined is the line number where the definition of the function starts. LineDefined int // LastLineDefined is the line number where the definition of the function ends. LastLineDefined int // NumUpvalues is the number of upvalues of the function. NumUpvalues uint8 // NumParams is the number of parameters of the function // (always 0 for Go functions). NumParams uint8 // IsVararg is true if the function is a variadic function // (always true for Go functions). IsVararg bool // IsTailCall is true if this function invocation was called by a tail call. // In this case, the caller of this level is not in the stack. IsTailCall bool }
Debug holds information about a function or an activation record.
type Function ¶
A Function is a callback for a Lua function implemented in Go. A Go function receives its arguments from Lua in its stack in direct order (the first argument is pushed first). So, when the function starts, State.Top returns the number of arguments received by the function. The first argument (if any) is at index 1 and its last argument is at index State.Top. To return values to Lua, a Go function just pushes them onto the stack, in direct order (the first result is pushed first), and returns in Go the number of results. Any other value in the stack below the results will be properly discarded by Lua. Like a Lua function, a Go function called by Lua can also return many results. To raise an error, return a Go error and the string result of its Error() method will be used as the error object.
func NewOpenBase ¶
func NewOpenBase(opts *BaseOptions) Function
NewOpenBase returns a Function that loads the basic library. The resulting function is intended to be used as an argument to Require.
func NewOpenMath ¶
func NewOpenMath(src RandomSource) Function
NewOpenMath returns a Function that loads the standard math library. If a RandomSource is provided, then it is used for random number generation.
The resulting function is intended to be used as an argument to Require.
type RandomSeed ¶
type RandomSeed [2]int64
RandomSeed is a 128-bit value used to initialize a RandomSource.
type RandomSource ¶
type RandomSource interface {
rand.Source
Seed(seed RandomSeed) (used RandomSeed)
}
A RandomSource is a source of uniformly distributed pseudo-random uint64 values in the range [0, 1<<64). Calling Seed should reinitialize the pseudo-random number generator and return the seed used such that passing the returned seed should produce the same sequence of values.
A RandomSource is not safe for concurrent use by multiple goroutines.
type Source ¶
Source is a description of Lua source. The zero value describes an empty literal string.
func AbstractSource ¶
AbstractSource returns a Source from a user-dependent description. The description can be retrieved later using [Source.Abstract].
The underlying string in an abstract source starts with "=".
func FilenameSource ¶
FilenameSource returns a Source for a filesystem path. The path can be retrieved later using [Source.Filename].
The underlying string in a filename source starts with "@".
func LiteralSource ¶
LiteralSource returns a Source for the given literal string. Because the type for a Source is determined by the first byte, if s starts with one of those symbols (which cannot occur in a syntactically valid Lua source file), then LiteralSource returns an AbstractSource with a condensed version of the string.
type State ¶
type State struct {
// contains filtered or unexported fields
}
A State is a Lua execution environment. The zero value is a ready-to-use environment with an empty stack and and an empty global table.
func (*State) AbsIndex ¶
AbsIndex converts the acceptable index idx into an equivalent absolute index (that is, one that does not depend on the stack size). AbsIndex panics if idx is not an acceptable index.
func (*State) Arithmetic ¶
Arithmetic performs an arithmetic or bitwise operation over the two values (or one, in the case of negations) at the top of the stack, with the value on the top being the second operand, pops these values, and pushes the result of the operation. The function follows the semantics of the corresponding Lua operator (that is, it may call metamethods). If there is an error, Arithmetic does not push anything onto the stack.
func (*State) Call ¶
Call calls a function (or callable object) in protected mode.
To do a call you must use the following protocol: first, the function to be called is pushed onto the stack; then, the arguments to the call are pushed in direct order; that is, the first argument is pushed first. Finally you call Call; nArgs is the number of arguments that you pushed onto the stack. When the function returns, all arguments and the function value are popped and the call results are pushed onto the stack. The number of results is adjusted to nResults, unless nResults is MultipleReturns. In this case, all results from the function are pushed; Lua takes care that the returned values fit into the stack space, but it does not ensure any extra space in the stack. The function results are pushed onto the stack in direct order (the first result is pushed first), so that after the call the last result is on the top of the stack. Call always removes the function and its arguments from the stack.
Error Handling ¶
If the msgHandler argument is 0, then if an error occurs during the function call, it is returned as a Go error value. (This is in contrast to the C Lua API which pushes an error object onto the stack.) Otherwise, msgHandler is the stack index of a message handler. In case of runtime errors, this handler will be called with the error object and Call will push its return value onto the stack. The return value's string value will be used as a Go error returned by Call.
Typically, the message handler is used to add more debug information to the error object, such as a stack traceback. Such information cannot be gathered after the return of a State method, since by then the stack will have been unwound.
func (*State) CheckStack ¶
CheckStack ensures that the stack has space for at least n extra elements, that is, that you can safely push up to n values into it. It returns false if it cannot fulfill the request, either because it would cause the stack to be greater than a fixed maximum size (typically at least several thousand elements) or because it cannot allocate memory for the extra space. This function never shrinks the stack; if the stack already has space for the extra elements, it is left unchanged.
func (*State) Close ¶
Close resets the state, Close returns an error and does nothing if any function calls are in-progress. After a successful call to Close:
- The stack will be empty.
- The registry will be initialized to its original state.
- Type-wide metatables are removed.
Unlike the Lua C API, calling Close is not necessary to clean up resources. States and their associated values are garbage-collected like other Go values.
func (*State) Compare ¶
Compare reports if the value at idx1 satisfies op when compared with the value at index idx2, following the semantics of the corresponding Lua operator (that is, it may call metamethods). If either of the indices are invalid, Compare returns false and an error.
func (*State) Concat ¶
Concat concatenates the n values at the top of the stack, pops them, and leaves the result on the top. If n is 1, the result is the single value on the stack (that is, the function does nothing); if n is 0, the result is the empty string. Concatenation is performed following the usual semantics of Lua.
If there is an error, Concat removes the n values from the top of the stack and returns the error.
func (*State) Copy ¶
Copy copies the element at index fromIdx into the valid index toIdx, replacing the value at that position. Values at other positions are not affected.
func (*State) CreateTable ¶
CreateTable creates a new empty table and pushes it onto the stack. nArr is a hint for how many elements the table will have as a sequence; nRec is a hint for how many other elements the table will have. Lua may use these hints to preallocate memory for the new table.
func (*State) Dump ¶
Dump marshals the function at the top of the stack into a binary chunk. If stripDebug is true, the binary representation may not include all debug information about the function, to save space.
func (*State) Field ¶
Field pushes onto the stack the value t[k], where t is the value at the given index. See State.Table for further information.
func (*State) FunctionForLevel ¶
FunctionForLevel pushes the function executing at the given level onto the stack. Level 0 is the current running function, whereas level n+1 is the function that has called level n (except for tail calls, which do not count in the stack). When called with a level greater than the call stack depth, FunctionForLevel returns false and pushes nothing.
func (*State) Global ¶
Global pushes onto the stack the value of the global with the given name, returning the type of that value.
As in Lua, this function may trigger a metamethod on the globals table for the "index" event. If there is any error, Global pushes nil, then returns TypeNil and the error.
func (*State) ID ¶
ID returns a generic identifier for the value at the given index. The value can be a userdata, a table, a thread, or a function; otherwise, ID returns 0. Different objects will give different identifiers. Typically this function is used only for hashing and debug information.
func (*State) Index ¶
Index pushes onto the stack the value t[i], where t is the value at the given index. See State.Table for further information.
func (*State) Info ¶
Info returns debug information about the function executing at the given level. Level 0 is the current running function, whereas level n+1 is the function that has called level n (except for tail calls, which do not count in the stack). When called with a level greater than the stack depth, Stack returns nil. The special level -1 indicates the function value pushed onto the top of the stack.
func (*State) Insert ¶
Insert moves the top element into the given valid index, shifting up the elements above this index to open space. If idx is a pseudo-index, Insert panics.
func (*State) IsFunction ¶
IsFunction reports if the value at the given index is a function (either Go or Lua).
func (*State) IsGoFunction ¶
IsGoFunction reports if the value at the given index is a Go function.
func (*State) IsInteger ¶
IsInteger reports if the value at the given index is an integer (that is, the value is a number and is represented as an integer).
func (*State) IsNoneOrNil ¶
IsNoneOrNil reports if the index is not valid or the value at this index is nil.
func (*State) IsNumber ¶
IsNumber reports if the value at the given index is a number or a string convertible to a number.
func (*State) IsString ¶
IsString reports if the value at the given index is a string or a number (which is always convertible to a string).
func (*State) IsUserdata ¶
IsUserdata reports if the value at the given index is a userdata (either full or light).
func (*State) Len ¶
Len pushes the length of the value at the given index to the stack. It is equivalent to the '#' operator in Lua and may trigger a metamethod for the "length" event.
If there is any error, Len pushes nil, then returns the error.
func (*State) Load ¶
Load loads a Lua chunk without running it. If there are no errors, Load pushes the compiled chunk as a Lua function on top of the stack.
The chunkName argument gives a name to the chunk, which is used for error messages and in debug information.
The string mode controls whether the chunk can be text or binary (that is, a precompiled chunk). It may be the string "b" (only binary chunks), "t" (only text chunks), or "bt" (both binary and text).
func (*State) Metatable ¶
Metatable reports whether the value at the given index has a metatable and if so, pushes that metatable onto the stack.
func (*State) NewUserdata ¶
NewUserdata creates and pushes on the stack a new full userdata, with numUserValues associated Lua values, called user values, plus the given Go value. The user values can be accessed or modified using *State.UserValue and *State.SetUserValue respectively. The stored Go value can be read using *State.ToUserdata.
func (*State) Next ¶
Next pops a key from the stack, and pushes a key–value pair from the table at the given index, the “next” pair after the given key. If there are no more elements in the table, then Next returns false and pushes nothing. Next panics if the value at the given index is not a table.
While traversing a table, avoid calling *State.ToString directly on a key, unless you know that the key is actually a string. Recall that *State.ToString may change the value at the given index; this confuses the next call to Next.
Unlike the C Lua API, Next has well-defined behavior if the table is modified during traversal or if the key is not present in the table. This implementation of Lua has a total ordering of keys, so Next always return the next key in ascending order.
Example ¶
package main import ( "context" "fmt" lua "zb.256lights.llc/pkg/internal/lua" ) func main() { ctx := context.Background() // Create an execution environment. state := new(lua.State) defer state.Close() // Create a table with a single pair to print. state.CreateTable(0, 1) state.PushString("bar") state.RawSetField(-2, "foo") // Iterate over table. tableIndex := state.AbsIndex(-1) state.PushNil() for state.Next(tableIndex) { // Format key at index -2. // We need to be careful not to use state.ToString on the key // without checking its type first, // since state.ToString may change the value on the stack. // We clone the value here to be safe. state.PushValue(-2) k, _, _ := lua.ToString(ctx, state, -1) state.Pop(1) // Format the value at index -1. v, _, _ := lua.ToString(ctx, state, -1) fmt.Printf("%s - %s\n", k, v) // Remove value, keeping key for the next iteration. state.Pop(1) } }
Output: foo - bar
func (*State) PushBoolean ¶
PushBoolean pushes a boolean onto the stack.
func (*State) PushClosure ¶
PushClosure pushes a Go closure onto the stack. n is how many upvalues this function will have, popped off the top of the stack. (When there are multiple upvalues, the first value is pushed first.) If n is negative or greater than 256, then PushClosure panics.
func (*State) PushInteger ¶
PushInteger pushes an integer onto the stack.
func (*State) PushNumber ¶
PushNumber pushes a floating point number onto the stack.
func (*State) PushString ¶
PushString pushes a string onto the stack.
func (*State) PushStringContext ¶
PushString pushes a string onto the stack with the given context arguments.
func (*State) RawEqual ¶
RawEqual reports whether the two values in the given indices are primitively equal (that is, equal without calling the __eq metamethod). If either index is invalid, then RawEqual reports false.
func (*State) RawField ¶
RawField pushes onto the stack t[k], where t is the value at the given index.
RawField does a raw access (i.e. without metamethods). RawField panics if the value at idx is not a table.
func (*State) RawGet ¶
RawGet pushes onto the stack t[k], where t is the value at the given index and k is the value on the top of the stack. This function pops the key from the stack, pushing the resulting value in its place.
RawGet does a raw access (i.e. without metamethods). The value at idx must be a table.
func (*State) RawIndex ¶
RawIndex pushes onto the stack the value t[n], where t is the table at the given index. The access is raw, that is, it does not use the __index metavalue. Returns the type of the pushed value.
func (*State) RawLen ¶
RawLen returns the raw "length" of the value at the given index: for strings, this is the string length; for tables, this is the result of the length operator ('#') with no metamethods; For other values, RawLen returns 0.
func (*State) RawSet ¶
RawSet does the equivalent to t[k] = v, where t is the value at the given index, v is the value on the top of the stack, and k is the value just below the top. This function pops both the key and the value from the stack. If the key from the stack cannot be used as a table key (i.e. it is nil or NaN), then RawSet returns an error.
func (*State) RawSetField ¶
RawSetField does the equivalent to t[k] = v, where t is the value at the given index and v is the value on the top of the stack. This function pops the value from the stack.
func (*State) RawSetIndex ¶
RawSetIndex does the equivalent of t[n] = v, where t is the table at the given index and v is the value on the top of the stack. This function pops the value from the stack. The assignment is raw, that is, it does not use the __newindex metavalue.
func (*State) Remove ¶
Remove removes the element at the given valid index, shifting down the elements above this index to fill the gap. This function cannot be called with a pseudo-index, because a pseudo-index is not an actual stack position.
func (*State) Replace ¶
Replace moves the top element into the given valid index without shifting any element (therefore replacing the value at that given index), and then pops the top element.
func (*State) Rotate ¶
Rotate rotates the stack elements between the valid index idx and the top of the stack. The elements are rotated n positions in the direction of the top, for a positive n, or -n positions in the direction of the bottom, for a negative n. If the absolute value of n is greater than the size of the slice being rotated, or if idx is a pseudo-index, Rotate panics.
func (*State) SetField ¶
SetField does the equivalent to t[k] = v, where t is the value at the given index, v is the value on the top of the stack, and k is the given string. This function pops the value from the stack. See State.SetTable for more information.
func (*State) SetGlobal ¶
SetGlobal pops a value from the stack and sets it as the new value of the global with the given name.
As in Lua, this function may trigger a metamethod on the globals table for the "newindex" event.
func (*State) SetIndex ¶
SetIndex does the equivalent to t[i] = v, where t is the value at the given index and v is the value on the top of the stack. This function pops the value from the stack. See State.SetTable for more information.
func (*State) SetMetatable ¶
SetMetatable pops a table or nil from the stack and sets that value as the new metatable for the value at the given index. (nil means no metatable.) SetMetatable panics if the top of the stack is not a table or nil.
func (*State) SetTable ¶
SetTable does the equivalent to t[k] = v, where t is the value at the given index, v is the value on the top of the stack, and k is the value just below the top. This function pops both the key and the value from the stack.
As in Lua, this function may trigger a metamethod for the "newindex" event.
func (*State) SetTop ¶
SetTop accepts any index, or 0, and sets the stack top to this index. If the new top is greater than the old one, then the new elements are filled with nil. If idx is 0, then all stack elements are removed.
func (*State) SetUpvalue ¶
SetUpvalue sets the value of a closure's upvalue. SetUpvalue assigns the value on the top of the stack to the upvalue, returns the upvalue's name, and also pops the value from the stack. Returns ("", false) when i is greater than the number of upvalues. The first upvalue is accessed with an i of 1.
func (*State) SetUserValue ¶
SetUserValue pops a value from the stack and sets it as the new n-th user value associated to the full userdata at the given index, reporting if the userdata has that value. (As with other Lua APIs, the first user value is n=1.) SetUserValue does nothing and returns false if the value at the given index is not a full userdata.
func (*State) StringContext ¶
StringContext returns any context values associated with the string at the given index. If the Lua value is not a string, the function returns nil.
func (*State) Table ¶
Table pushes onto the stack the value t[k], where t is the value at the given index and k is the value on the top of the stack. Returns the type of the pushed value.
This function pops the key from the stack, pushing the resulting value in its place.
As in Lua, this function may trigger a metamethod for the "index" event. If there is any error, Table pushes nil, then returns TypeNil and the error. Table always removes the key from the stack.
func (*State) ToBoolean ¶
ToBoolean converts the Lua value at the given index to a boolean value. Like all tests in Lua, ToBoolean returns true for any Lua value different from false and nil; otherwise it returns false.
func (*State) ToInteger ¶
ToInteger converts the Lua value at the given index to a signed 64-bit integer. The Lua value must be an integer, a number, or a string convertible to an integer; otherwise, ToInteger returns (0, false). ok is true if the operation succeeded.
func (*State) ToNumber ¶
ToNumber converts the Lua value at the given index to a floating point number. The Lua value must be a number or a string convertible to a number; otherwise, ToNumber returns (0, false). ok is true if the operation succeeded.
func (*State) ToString ¶
ToString converts the Lua value at the given index to a Go string. The Lua value must be a string or a number; otherwise, the function returns ("", false). If the value is a number, then ToString also changes the actual value in the stack to a string. (This change confuses State.Next when ToString is applied to keys during a table traversal.)
func (*State) ToUserdata ¶
ToUserdata returns the Go value stored in the userdata at the given index or (nil, false) if the value at the given index is not userdata.
func (*State) Top ¶
Top returns the index of the top element in the stack. Because indices start at 1, this result is equal to the number of elements in the stack; in particular, 0 means an empty stack.
func (*State) Type ¶
Type returns the type of the value in the given valid index, or TypeNone for a non-valid but acceptable index.
func (*State) Upvalue ¶
Upvalue gets information about the i'th upvalue of the closure at funcIndex. Upvalue pushes the upvalue's value onto the stack and returns its name. Returns ("", false) and pushes nothing when i is greater than the number of upvalues. The first upvalue is accessed with an i of 1.
func (*State) UserValue ¶
UserValue pushes onto the stack the n-th user value associated with the full userdata at the given index and returns the type of the pushed value. If the userdata does not have that value or the value at the given index is not a full userdata, UserValue pushes nil and returns TypeNone. (As with other Lua APIs, the first user value is n=1.)
type Type ¶
type Type int
Type is an enumeration of Lua data types.
const ( TypeNil Type = 0 TypeBoolean Type = 1 TypeLightUserdata Type = 2 TypeNumber Type = 3 TypeString Type = 4 TypeTable Type = 5 TypeFunction Type = 6 TypeUserdata Type = 7 TypeThread Type = 8 )
Value types.
const TypeNone Type = -1
TypeNone is the value returned from State.Type for a non-valid but acceptable index.
func Metafield ¶
Metafield pushes onto the stack the field event from the metatable of the object at index obj and returns the type of the pushed value. If the object does not have a metatable, or if the metatable does not have this field, pushes nothing and returns TypeNil.
func Metatable ¶
Metatable pushes onto the stack the metatable associated with the name tname in the registry (see NewMetatable), or nil if there is no metatable associated with that name. Returns the type of the pushed value.