Documentation ¶
Overview ¶
Package lua provides low-level bindings for Lua 5.4.
Relationship to C API ¶
This package attempts to be a mostly one-to-one mapping with the Lua C API. The methods on State and ActivationRecord are the primitive functions (i.e. the library functions that start with "lua_"). Functions in this package mostly correspond to the auxiliary library (i.e. the library functions that start with "luaL_"), but are pure Go reimplementations of these functions, usually with Go-specific niceties.
Example ¶
package main import ( "log" "zombiezen.com/go/lua" ) func main() { // Create an execution environment // and make the standard libraries available. state := new(lua.State) defer state.Close() if err := lua.OpenLibraries(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.LoadString(luaSource, luaSource, "t"); err != nil { log.Fatal(err) } if err := state.Call(0, 0, 0); err != nil { log.Fatal(err) } }
Output: Hello, World!
Index ¶
- Constants
- func CallMeta(l *State, obj int, event string) (bool, error)
- func CheckInteger(l *State, arg int) (int64, error)
- func CheckString(l *State, arg int) (string, error)
- func CheckUserdata(l *State, arg int, tname string) ([]byte, error)
- func IsHandlerError(err error) bool
- func IsOutOfMemory(err error) bool
- func IsSyntax(err error) bool
- func IsYield(err error) bool
- func Len(l *State, idx int) (int64, error)
- func NewArgError(l *State, arg int, msg string) error
- func NewLib(l *State, reg map[string]Function) error
- func NewMetatable(l *State, tname string) bool
- func NewTypeError(l *State, arg int, tname string) error
- func OpenCoroutine(l *State) (int, error)
- func OpenDebug(l *State) (int, error)
- func OpenLibraries(l *State) error
- func OpenPackage(l *State) (int, error)
- func OpenString(l *State) (int, error)
- func OpenTable(l *State) (int, error)
- func OpenUTF8(l *State) (int, error)
- func PushFile(l *State, f ReadWriteSeekCloser) error
- func PushPipe(l *State, rw io.ReadWriteCloser) error
- func PushReader(l *State, r io.ReadCloser) error
- func PushWriter(l *State, w io.WriteCloser) error
- func Require(l *State, modName string, global bool, openf Function) error
- func SetFuncs(l *State, nUp int, reg map[string]Function) error
- func SetMetatable(l *State, tname string)
- func Subtable(l *State, idx int, fname string) (bool, error)
- func TestUserdata(l *State, idx int, tname string) []byte
- func ToString(l *State, idx int) (string, error)
- func UpvalueIndex(i int) int
- func Where(l *State, level int) string
- type ActivationRecord
- type Debug
- type Function
- type IOLibrary
- type OSLibrary
- type ReadWriteSeekCloser
- type State
- func (l *State) AbsIndex(idx int) int
- func (l *State) Call(nArgs, nResults, msgHandler int) error
- func (l *State) CheckStack(n int) bool
- func (l *State) Close() error
- func (l *State) Copy(fromIdx, toIdx int)
- func (l *State) CopyUserdata(dst []byte, idx, start int) int
- func (l *State) CreateTable(nArr, nRec int)
- func (l *State) Dump(w io.Writer, strip bool) (int64, error)
- func (l *State) Field(idx int, k string, msgHandler int) (Type, error)
- func (l *State) GC()
- func (l *State) GCCount() int64
- func (l *State) GCGenerational(minorMul, majorMul int)
- func (l *State) GCIncremental(pause, stepMul, stepSize int)
- func (l *State) GCRestart()
- func (l *State) GCStep(stepSize int)
- func (l *State) GCStop()
- func (l *State) Global(name string, msgHandler int) (Type, error)
- func (l *State) Info(what string) *Debug
- func (l *State) Insert(idx int)
- func (l *State) IsBoolean(idx int) bool
- func (l *State) IsFunction(idx int) bool
- func (l *State) IsGCRunning() bool
- func (l *State) IsInteger(idx int) bool
- func (l *State) IsNativeFunction(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) IsThread(idx int) bool
- func (l *State) IsUserdata(idx int) bool
- func (l *State) Len(idx, msgHandler int) error
- func (l *State) Load(r io.Reader, chunkName string, mode string) error
- func (l *State) LoadString(s string, chunkName string, mode string) error
- func (l *State) Metatable(idx int) bool
- func (l *State) NewUserdataUV(size, nUValue 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(n int64)
- func (l *State) PushLightUserdata(p uintptr)
- func (l *State) PushNil()
- func (l *State) PushNumber(n float64)
- func (l *State) PushString(s 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)
- 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(idx int, k string, msgHandler int) error
- func (l *State) SetGlobal(name string, msgHandler int) error
- func (l *State) SetMetatable(objIndex int)
- func (l *State) SetTable(idx, msgHandler int) error
- func (l *State) SetTop(idx int)
- func (l *State) SetUserValue(idx int, n int) bool
- func (l *State) SetUserdata(idx int, start int, src []byte)
- func (l *State) Stack(level int) *ActivationRecord
- func (l *State) Table(idx, msgHandler 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) ToPointer(idx int) uintptr
- func (l *State) ToString(idx int) (s string, ok bool)
- func (l *State) Top() int
- func (l *State) Type(idx int) Type
- func (l *State) UserValue(idx int, n int) Type
- type Type
Examples ¶
Constants ¶
const ( VersionNum = lua54.VersionNum VersionReleaseNum = lua54.VersionReleaseNum )
Version number.
const ( // Version is the version string without the final "release" number. Version = lua54.Version // Release is the full version string. Release = lua54.Release // Copyright is the full version string with a copyright notice. Copyright = lua54.Copyright // Authors is a string listing the authors of Lua. Authors = lua54.Copyright VersionMajor = lua54.VersionMajor VersionMinor = lua54.VersionMinor VersionRelease = lua54.VersionRelease )
Version strings.
const ( // RegistryIndexMainThread is the index at which the registry has the main thread of the state. RegistryIndexMainThread int64 = lua54.RegistryIndexMainThread // RegistryIndexGlobals is the index at which the registry has the global environment. RegistryIndexGlobals int64 = lua54.RegistryIndexGlobals // LoadedTable is the key in the registry for the table of loaded modules. LoadedTable = lua54.LoadedTable // PreloadTable is the key in the registry for the table of preloaded loaders. PreloadTable = lua54.PreloadTable )
Predefined keys in the registry.
const ( GName = lua54.GName CoroutineLibraryName = lua54.CoroutineLibraryName TableLibraryName = lua54.TableLibraryName IOLibraryName = lua54.IOLibraryName OSLibraryName = lua54.OSLibraryName StringLibraryName = lua54.StringLibraryName UTF8LibraryName = lua54.UTF8LibraryName MathLibraryName = lua54.MathLibraryName DebugLibraryName = lua54.DebugLibraryName PackageLibraryName = lua54.PackageLibraryName )
Standard library names.
const MultipleReturns int = lua54.MultipleReturns
MultipleReturns is the option for multiple returns in State.Call.
const RegistryIndex int = lua54.RegistryIndex
RegistryIndex is a pseudo-index to the registry, a predefined table that can be used by any Go or C code to store whatever Lua values it needs to store.
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 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 block of bytes 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 IsHandlerError ¶
IsHandlerError reports whether the error indicates an error while running the message handler.
func IsOutOfMemory ¶
IsOutOfMemory reports whether the error indicates a memory allocation error.
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 OpenCoroutine ¶
OpenCoroutine loads the standard coroutine library. This function is intended to be used as an argument to Require.
func OpenDebug ¶
OpenDebug loads the standard debug library. This function is intended to be used as an argument to Require.
func OpenLibraries ¶
OpenLibraries opens all standard Lua libraries into the given state with their default settings.
func OpenPackage ¶
OpenPackage loads the standard package library. This function is intended to be used as an argument to Require.
func OpenString ¶
OpenString loads the standard string library. This function is intended to be used as an argument to Require.
func OpenTable ¶
OpenTable loads the standard table library. This function is intended to be used as an argument to Require.
func OpenUTF8 ¶
OpenUTF8 loads the standard utf8 library. This function is intended to be used as an argument to Require.
func PushFile ¶
func PushFile(l *State, f ReadWriteSeekCloser) error
PushFile pushes a Lua file object onto the stack that reads, writes, and seeks using f.
func PushPipe ¶
func PushPipe(l *State, rw io.ReadWriteCloser) error
PushPipe pushes a Lua file object onto the stack that reads and writes to rw.
func PushReader ¶
func PushReader(l *State, r io.ReadCloser) error
PushReader pushes a Lua file object onto the stack that reads from the given reader. If the reader also implements io.Seeker, then the file object's seek method will use it.
func PushWriter ¶
func PushWriter(l *State, w io.WriteCloser) error
PushWriter pushes a Lua file object onto the stack that writes to the given writer. If the writer also implements io.Seeker, then the file object's seek method will use it.
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 block of bytes for the userdata at the given index. TestUserdata returns non-nil if and only if the value at the given index is a userdata and has the type tname (see NewMetatable).
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 UpvalueIndex ¶
UpvalueIndex returns the pseudo-index that represents the i-th upvalue of the running function. If i is outside the range [1, 255], 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 ActivationRecord ¶
type ActivationRecord struct {
// contains filtered or unexported fields
}
An ActivationRecord is a reference to a function invocation's activation record.
func (*ActivationRecord) Info ¶
func (ar *ActivationRecord) Info(what string) *Debug
Info gets information about the function invocation. The what string is the same as for State.Info. If Info is called on a nil ActivationRecord or the State it originated from has been closed, then Info returns nil.
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 Info functions check 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, // "C" if it is a C or 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. // If source starts with a '@', // it means that the function was defined in a file where the file name follows the '@'. // If source starts with a '=', // the remainder of its contents describes the source in a user-dependent manner. // Otherwise, the function was defined in a string where source is that string. Source string // ShortSource is a "printable" version of source, to be used in error messages. ShortSource string // 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/C functions). NumParams uint8 // IsVararg is true if the function is a variadic function // (always true for Go/C 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 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 ¶
NewOpenBase returns a Function that loads the basic library. The print function will write to the given out writer (or os.Stdout if nil). If loadfile is not nil, then loadfile will be replaced by the given implementation and dofile will use it to load files. The resulting function is intended to be used as an argument to Require.
func NewOpenMath ¶
NewOpenMath returns a Function that loads the standard math library. If a rand.Source is provided, then it is used instead of Lua's built-in random number generator. The resulting function is intended to be used as an argument to Require.
type IOLibrary ¶
type IOLibrary struct { // Stdin is the reader for io.stdin. // If nil, stdin will act like an empty file. Stdin io.ByteReader // Stdout is the writer for io.stdout. // If nil, io.stdout will discard any data written to it. Stdout io.Writer // Stderr is the writer for io.stderr. // If nil, io.stderr will discard any data written to it. Stderr io.Writer // Open opens a file with the given name and [mode]. // The returned file should implement io.Reader and/or io.Writer, // and may optionally implement io.ByteReader and/or io.Seeker. // // [mode]: https://www.lua.org/manual/5.4/manual.html#pdf-io.open Open func(name, mode string) (io.Closer, error) // CreateTemp returns a handle for a temporary file opened in update mode. // The returned file should clean up the file on Close. CreateTemp func() (ReadWriteSeekCloser, error) // OpenProcessReader starts a subprocess // and returns a handle for reading its standard output. // If nil, io.popen(command, "r") will return an error. OpenProcessReader func(command string) (io.ReadCloser, error) // OpenProcessWriter starts a subprocess // and returns a handle for writing to its standard input. // If nil, io.popen(command, "w") will return an error. OpenProcessWriter func(command string) (io.WriteCloser, error) }
IOLibrary is a pure Go implementation of the standard Lua "io" library. The zero value of IOLibrary stubs out all functionality.
func NewIOLibrary ¶
func NewIOLibrary() *IOLibrary
NewIOLibrary returns an OSLibrary that uses the native operating system.
type OSLibrary ¶
type OSLibrary struct { // Now returns the current local time. // If nil, uses time.Now. Now func() time.Time // Location returns the local timezone. // If nil, uses time.Local. Location func() *time.Location // LookupEnv returns the value of the given process environment variable. // If nil, os.getenv will always return nil. LookupEnv func(string) (string, bool) // Remove deletes the given file. // If nil, os.remove will always return nil and an error message. Remove func(string) error // Rename renames the given file. // If nil, os.rename will always return nil and an error message. Rename func(oldname, newname string) error // Execute runs a subprocess in the operating system shell. // If nil, os.execute with an argument will always return nil. Execute func(command string) (ok bool, result string, status int) // HasShell reports whether a shell is available. // If nil, os.execute without an argument will always return false. HasShell func() bool // TempName should return a file name that can be used for a temporary file. // If nil, os.tmpname will always raise an error. TempName func() (string, error) }
OSLibrary is a pure Go implementation of the standard Lua "os" library. The zero value of OSLibrary stubs out any functionality not related to time.
func NewOSLibrary ¶
func NewOSLibrary() *OSLibrary
NewOSLibrary returns an OSLibrary that uses the native operating system.
type ReadWriteSeekCloser ¶
ReadWriteSeekCloser is an interface that groups the basic Read, Write, Seek, and Close methods.
type State ¶
type State struct {
// contains filtered or unexported fields
}
State represents a Lua execution thread. The zero value is a state with a single main thread, an empty stack, and an empty environment.
Methods that take in stack indices have a notion of valid and acceptable indices. If a method receives a stack index that is not within range, it will panic. Methods may also panic if there is insufficient stack space. Use State.CheckStack to ensure that the State has sufficient stack space before making calls, but note that any new State or called function will support pushing at least 20 values.
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) 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.
If there is any error, Call catches it, pushes a single value on the stack (the error object), and returns an error. Call always removes the function and its arguments from the stack.
If msgHandler is 0, then the error object returned on the stack is exactly the original error object. Otherwise, msgHandler is the stack index of a message handler. (This index cannot be a pseudo-index.) In case of runtime errors, this handler will be called with the error object and its return value will be the object returned on the stack 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 Call, since by then the stack has 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 releases all resources associated with the state. Making further calls to the State will create a new execution environment.
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) CopyUserdata ¶
CopyUserdata copies bytes from the userdata's block of bytes to dst if the value at the given index is a full userdata. It returns the number of bytes copied.
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 dumps a function as a binary chunk to the given writer. Receives a Lua function on the top of the stack and produces a binary chunk that, if loaded again, results in a function equivalent to the one dumped. If strip is true, the binary representation may not include all debug information about the function, to save space. Dump does not pop the Lua function from the stack. Returns the number of bytes written and the first error that occurred.
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) GC ¶
func (l *State) GC()
GC performs a full garbage-collection cycle.
This function should not be called by a Lua finalizer.
func (*State) GCCount ¶
GCCount returns the current amount of memory (in bytes) in use by Lua.
This function should not be called by a Lua finalizer.
func (*State) GCGenerational ¶
GCGenerational changes the collector to generational mode with the given parameters.
This function should not be called by a Lua finalizer.
func (*State) GCIncremental ¶
GCIncremental changes the collector to incremental mode with the given parameters.
This function should not be called by a Lua finalizer.
func (*State) GCRestart ¶
func (l *State) GCRestart()
GCRestart restarts the garbage collector.
This function should not be called by a Lua finalizer.
func (*State) GCStep ¶
GCStep performs an incremental step of garbage collection, corresponding to the allocation of stepSize kibibytes.
This function should not be called by a Lua finalizer.
func (*State) GCStop ¶
func (l *State) GCStop()
GCStop stops the garbage collector.
This function should not be called by a Lua finalizer.
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 catches it, pushes a single value on the stack (the error object), and returns an error with TypeNil.
If msgHandler is 0, then the error object returned on the stack is exactly the original error object. Otherwise, msgHandler is the stack index of a message handler. (This index cannot be a pseudo-index.) In case of runtime errors, this handler will be called with the error object and its return value will be the object returned on the stack by Table. 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 Table, since by then the stack has unwound.
func (*State) Info ¶
Info gets information about a specific function. Each character in the string what selects some fields of the Debug structure to be filled or a value to be pushed on the stack.
- 'f': pushes onto the stack the function that is running at the given level;
- 'l': fills in the field CurrentLine;
- 'n': fills in the fields Name and NameWhat;
- 'S': fills in the fields Source, ShortSource, LineDefined, LastLineDefined, and What;
- 't': fills in the field IsTailCall;
- 'u': fills in the fields NumUpvalues, NumParams, and IsVararg;
- 'L': pushes onto the stack a table whose indices are the lines on the function with some associated code, that is, the lines where you can put a break point. (Lines with no code include empty lines and comments.) If this option is given together with option 'f', its table is pushed after the function.
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 (any of C, Go, or Lua).
func (*State) IsGCRunning ¶
IsGCRunning reports whether the garbage collector is running (i.e. not stopped).
This function should not be called by a Lua finalizer.
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) IsNativeFunction ¶
IsNativeFunction reports if the value at the given index is a C or Go function.
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 catches it, pushes a single value on the stack (the error object), and returns an error.
If msgHandler is 0, then the error object returned on the stack is exactly the original error object. Otherwise, msgHandler is the stack index of a message handler. (This index cannot be a pseudo-index.) In case of runtime errors, this handler will be called with the error object and its return value will be the object returned on the stack by Len. 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 Len, since by then the stack has unwound.
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. Otherwise, it pushes an error message.
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) LoadString ¶
LoadString loads a Lua chunk from a string without running it. It behaves the same as State.Load, but takes in a string instead of an io.Reader.
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) NewUserdataUV ¶
NewUserdataUV creates and pushes on the stack a new full userdata, with nUValue associated Lua values, called user values, plus an associated block of size bytes. The user values can be accessed or modified using State.UserValue and State.SetUserValue respectively. The block of bytes can be set and read using State.SetUserdata and State.CopyUserdata respectively.
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.
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.
This behavior of this function is undefined if the given key is neither nil nor present in the table. See function next for the caveats of modifying the table during its traversal.
Example ¶
package main import ( "fmt" "zombiezen.com/go/lua" ) func main() { // 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(state, -1) state.Pop(1) // Format the value at index -1. v, _ := lua.ToString(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 254, then PushClosure panics.
Under the hood, PushClosure uses the first Lua upvalue to store a reference to the Go function. UpvalueIndex already compensates for this, so the first upvalue you push with PushClosure can be accessed with UpvalueIndex(1). As such, this implementation detail is largely invisible except in debug interfaces. No assumptions should be made about the content of the first upvalue, as it is subject to change, but it is guaranteed that PushClosure will use exactly one upvalue.
func (*State) PushInteger ¶
PushInteger pushes an integer onto the stack.
func (*State) PushLightUserdata ¶
PushLightUserdata pushes a light userdata onto the stack.
Userdata represent C or Go values in Lua. A light userdata represents a pointer. It is a value (like a number): you do not create it, it has no individual metatable, and it is not collected (as it was never created). A light userdata is equal to "any" light userdata with the same address.
func (*State) PushNumber ¶
PushNumber pushes a floating point number onto the stack.
func (*State) PushString ¶
PushString pushes a string onto the stack.
func (*State) RawEqual ¶
RawEqual reports whether the two values in the given indices are primitively equal (that is, equal without calling the __eq metamethod).
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). The value at idx must be 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 userdata, this is the size of the block of memory allocated for the userdata. 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.
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. If there is any error, SetGlobal catches it, pushes a single value on the stack (the error object), and returns an error. SetGlobal always removes the value from the stack.
If msgHandler is 0, then the error object returned on the stack is exactly the original error object. Otherwise, msgHandler is the stack index of a message handler. (This index cannot be a pseudo-index.) In case of runtime errors, this handler will be called with the error object and its return value will be the object returned on the stack by SetGlobal. 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 SetGlobal, since by then the stack has unwound.
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.)
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. If there is any error, SetTable catches it, pushes a single value on the stack (the error object), and returns an error. SetTable always removes the key and value from the stack.
If msgHandler is 0, then the error object returned on the stack is exactly the original error object. Otherwise, msgHandler is the stack index of a message handler. (This index cannot be a pseudo-index.) In case of runtime errors, this handler will be called with the error object and its return value will be the object returned on the stack by SetTable. 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 SetTable, since by then the stack has unwound.
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) 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.)
func (*State) SetUserdata ¶
SetUserdata copies the bytes from src to the userdata's block of bytes, starting at the given start byte position. SetUserdata panics if start+len(src) is greater than the size of the userdata's block of bytes.
func (*State) Stack ¶
func (l *State) Stack(level int) *ActivationRecord
Stack returns an identifier of the activation record of 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.
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 catches it, pushes a single value on the stack (the error object), and returns an error with TypeNil. Table always removes the key from the stack.
If msgHandler is 0, then the error object returned on the stack is exactly the original error object. Otherwise, msgHandler is the stack index of a message handler. (This index cannot be a pseudo-index.) In case of runtime errors, this handler will be called with the error object and its return value will be the object returned on the stack by Table. 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 Table, since by then the stack has unwound.
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) ToPointer ¶
ToPointer converts the value at the given index to a generic pointer and returns its numeric address. The value can be a userdata, a table, a thread, a string, or a function; otherwise, ToPointer returns 0. Different objects will give different addresses. Typically this function is used only for hashing and debug information.
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) 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) 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, pushes nil and returns TypeNone. (As with other Lua APIs, the first user value is n=1.)
type Type ¶
Type is an enumeration of Lua data types.
const ( TypeNil Type = Type(lua54.TypeNil) TypeBoolean Type = Type(lua54.TypeBoolean) TypeLightUserdata Type = Type(lua54.TypeLightUserdata) TypeNumber Type = Type(lua54.TypeNumber) TypeString Type = Type(lua54.TypeString) TypeTable Type = Type(lua54.TypeTable) TypeFunction Type = Type(lua54.TypeFunction) TypeUserdata Type = Type(lua54.TypeUserdata) TypeThread Type = Type(lua54.TypeThread) )
Value types.
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.
Source Files ¶
Directories ¶
Path | Synopsis |
---|---|
cmd
|
|
zombiezen-lua
zombiezen-lua is a standalone Lua interpreter.
|
zombiezen-lua is a standalone Lua interpreter. |
internal
|
|
bufseek
Package bufseek provides a buffered io.Reader that also implements io.Seeker.
|
Package bufseek provides a buffered io.Reader that also implements io.Seeker. |