lua

package
v0.0.0-...-15c7053 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jan 22, 2025 License: MIT Imports: 23 Imported by: 0

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

Examples

Constants

View Source
const (
	VersionNum = 504

	VersionMajor = 5
	VersionMinor = 4
)

Version numbers.

View Source
const GName = "_G"

GName is the name of the global table.

View Source
const LoadedTable = "_LOADED"

LoadedTable is the key in the registry for table of loaded modules.

View Source
const MathLibraryName = "math"

MathLibraryName is the conventional identifier for the math library.

View Source
const MultipleReturns = luacode.MultiReturn

MultipleReturns is the sentinel that indicates that an arbitrary number of result values are accepted.

View Source
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.

View Source
const (
	RegistryIndexGlobals int64 = 2
)

Predefined values in the registry.

View Source
const StringLibraryName = "string"

StringLibraryName is the conventional identifier for the string manipulation library.

View Source
const TableLibraryName = "table"

TableLibraryName is the conventional identifier for the table manipulation library.

View Source
const UnknownSource = luacode.UnknownSource

UnknownSource is a placeholder for an unknown Source.

View Source
const Version = "Lua 5.4"

Version is the version string without the final "release" number.

Variables

This section is empty.

Functions

func CallMeta

func CallMeta(ctx context.Context, l *State, obj int, event string) (bool, error)

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

func CheckInteger(l *State, arg int) (int64, error)

CheckInteger checks whether the function argument arg is an integer (or can be converted to an integer) and returns this integer.

func CheckNumber

func CheckNumber(l *State, arg int) (float64, error)

CheckNumber checks whether the function argument arg is a number and returns this number.

func CheckString

func CheckString(l *State, arg int) (string, error)

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

func CheckUserdata(l *State, arg int, tname string) (any, error)

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 Len

func Len(ctx context.Context, l *State, idx int) (int64, error)

Len returns the "length" of the value at the given index as an integer.

func NewArgError

func NewArgError(l *State, arg int, msg string) error

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 NewLib

func NewLib(l *State, reg map[string]Function)

NewLib creates a new table and registers there the functions in the map reg.

func NewMetatable

func NewMetatable(l *State, tname string) bool

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

func NewTypeError(l *State, arg int, tname string) error

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

func OpenLibraries(ctx context.Context, l *State) error

OpenLibraries opens all standard Lua libraries into the given state with their default settings.

func OpenString

func OpenString(ctx context.Context, l *State) (int, error)

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

func OpenTable(ctx context.Context, l *State) (int, error)

OpenTable is a Function that loads the table manipulation library. This function is intended to be used as an argument to Require.

func Require

func Require(ctx context.Context, l *State, modName string, global bool, openf Function) error

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

func SetFuncs(ctx context.Context, l *State, nUp int, reg map[string]Function) error

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

func SetMetatable(l *State, tname string)

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

func Subtable(ctx context.Context, l *State, idx int, fname string) (bool, error)

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

func TestUserdata(l *State, idx int, tname string) (_ any, isUserdata bool)

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

func ToConstant(l *State, idx int) (_ luacode.Value, ok bool)

ToConstant converts the nil, boolean, number, or string at the given index to a luacode.Value.

func ToString

func ToString(ctx context.Context, l *State, idx int) (string, sets.Set[string], error)

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

func Traceback(l *State, msg string, level int) string

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

func UpvalueIndex(i int) int

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

func Where(l *State, level int) string

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

type Function func(ctx context.Context, l *State) (int, error)

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

type Source = luacode.Source

Source is a description of Lua source. The zero value describes an empty literal string.

func AbstractSource

func AbstractSource(description string) Source

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

func FilenameSource(path string) Source

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

func LiteralSource(s string) Source

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

func (l *State) AbsIndex(idx int) int

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

func (l *State) Arithmetic(ctx context.Context, op luacode.ArithmeticOperator) error

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

func (l *State) Call(ctx context.Context, nArgs, nResults, msgHandler int) error

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

func (l *State) CheckStack(n int) bool

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

func (l *State) Close() error

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

func (l *State) Compare(ctx context.Context, idx1, idx2 int, op ComparisonOperator) (bool, error)

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

func (l *State) Concat(ctx context.Context, n int) error

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

func (l *State) Copy(fromIdx, toIdx int)

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

func (l *State) CreateTable(nArr, nRec int)

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

func (l *State) Dump(stripDebug bool) ([]byte, error)

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

func (l *State) Field(ctx context.Context, idx int, k string) (Type, error)

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

func (l *State) FunctionForLevel(level int) bool

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

func (l *State) Global(ctx context.Context, name string) (Type, error)

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

func (l *State) ID(idx int) uint64

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

func (l *State) Index(ctx context.Context, idx int, i int64) (Type, error)

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

func (l *State) Info(level int) *Debug

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

func (l *State) Insert(idx int)

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) IsBoolean

func (l *State) IsBoolean(idx int) bool

IsBoolean reports if the value at the given index is a boolean.

func (*State) IsFunction

func (l *State) IsFunction(idx int) bool

IsFunction reports if the value at the given index is a function (either Go or Lua).

func (*State) IsGoFunction

func (l *State) IsGoFunction(idx int) bool

IsGoFunction reports if the value at the given index is a Go function.

func (*State) IsInteger

func (l *State) IsInteger(idx int) bool

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) IsNil

func (l *State) IsNil(idx int) bool

IsNil reports if the value at the given index is nil.

func (*State) IsNone

func (l *State) IsNone(idx int) bool

IsNone reports if the index is not valid.

func (*State) IsNoneOrNil

func (l *State) IsNoneOrNil(idx int) bool

IsNoneOrNil reports if the index is not valid or the value at this index is nil.

func (*State) IsNumber

func (l *State) IsNumber(idx int) bool

IsNumber reports if the value at the given index is a number or a string convertible to a number.

func (*State) IsString

func (l *State) IsString(idx int) bool

IsString reports if the value at the given index is a string or a number (which is always convertible to a string).

func (*State) IsTable

func (l *State) IsTable(idx int) bool

IsTable reports if the value at the given index is a table.

func (*State) IsUserdata

func (l *State) IsUserdata(idx int) bool

IsUserdata reports if the value at the given index is a userdata (either full or light).

func (*State) Len

func (l *State) Len(ctx context.Context, idx int) error

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

func (l *State) Load(r io.ByteScanner, chunkName Source, mode string) (err error)

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

func (l *State) Metatable(idx int) bool

Metatable reports whether the value at the given index has a metatable and if so, pushes that metatable onto the stack.

func (*State) NewUserdata

func (l *State) NewUserdata(x any, numUserValues int)

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

func (l *State) Next(idx int) bool

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) Pop

func (l *State) Pop(n int)

Pop pops n elements from the stack.

func (*State) PushBoolean

func (l *State) PushBoolean(b bool)

PushBoolean pushes a boolean onto the stack.

func (*State) PushClosure

func (l *State) PushClosure(n int, f Function)

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

func (l *State) PushInteger(i int64)

PushInteger pushes an integer onto the stack.

func (*State) PushNil

func (l *State) PushNil()

PushNil pushes a nil value onto the stack.

func (*State) PushNumber

func (l *State) PushNumber(n float64)

PushNumber pushes a floating point number onto the stack.

func (*State) PushString

func (l *State) PushString(s string)

PushString pushes a string onto the stack.

func (*State) PushStringContext

func (l *State) PushStringContext(s string, context sets.Set[string])

PushString pushes a string onto the stack with the given context arguments.

func (*State) PushValue

func (l *State) PushValue(idx int)

PushValue pushes a copy of the element at the given index onto the stack.

func (*State) RawEqual

func (l *State) RawEqual(idx1, idx2 int) bool

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

func (l *State) RawField(idx int, k string) Type

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

func (l *State) RawGet(idx int) Type

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

func (l *State) RawIndex(idx int, n int64) Type

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

func (l *State) RawLen(idx int) uint64

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

func (l *State) RawSet(idx int) error

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

func (l *State) RawSetField(idx int, k string)

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

func (l *State) RawSetIndex(idx int, n int64)

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

func (l *State) Remove(idx int)

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

func (l *State) Replace(idx int)

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

func (l *State) Rotate(idx, n int)

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

func (l *State) SetField(ctx context.Context, idx int, k string) error

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

func (l *State) SetGlobal(ctx context.Context, name string) error

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

func (l *State) SetIndex(ctx context.Context, idx int, i int64) error

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

func (l *State) SetMetatable(idx int)

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

func (l *State) SetTable(ctx context.Context, idx int) error

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

func (l *State) SetTop(idx int)

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

func (l *State) SetUpvalue(funcIndex int, i int) (upvalueName string, ok bool)

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

func (l *State) SetUserValue(idx int, n int) bool

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

func (l *State) StringContext(idx int) sets.Set[string]

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

func (l *State) Table(ctx context.Context, idx int) (Type, error)

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

func (l *State) ToBoolean(idx int) bool

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

func (l *State) ToInteger(idx int) (n int64, ok bool)

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

func (l *State) ToNumber(idx int) (n float64, ok bool)

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

func (l *State) ToString(idx int) (s string, ok bool)

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

func (l *State) ToUserdata(idx int) (_ any, isUserdata bool)

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

func (l *State) Top() int

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

func (l *State) Type(idx int) 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

func (l *State) Upvalue(funcIndex int, i int) (upvalueName string, ok bool)

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

func (l *State) UserValue(idx int, n int) Type

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

func Metafield(l *State, obj int, event string) Type

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

func Metatable(l *State, tname string) Type

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.

func (Type) String

func (tp Type) String() string

String returns the name of the type encoded by the value tp.

type WarnFunc

type WarnFunc func(msg string, toBeContinued bool)

WarnFunc is a function that implements Warner.

func (WarnFunc) Warn

func (f WarnFunc) Warn(msg string, toBeContinued bool)

Warn calls the function to implement Warner.

type Warner

type Warner interface {
	Warn(msg string, toBeContinued bool)
}

A Warner handles warnings from the basic “warn” Lua function.

Warn handles a single warning argument. toBeContinued is true if there are more arguments to this call to “warn”.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL