go-lua: github.com/Shopify/go-lua Index | Examples | Files

package lua

import "github.com/Shopify/go-lua"

Package lua is a port of the Lua VM from http://lua.org/ from C to Go.


package main

import (

type step struct {
    name     string
    function interface{}

func main() {
    steps := []step{}
    l := lua.NewState()
    _ = lua.NewMetaTable(l, "stepMetaTable")
    lua.SetFunctions(l, []lua.RegistryFunction{{"__newindex", func(l *lua.State) int {
        k, v := lua.CheckString(l, 2), l.ToValue(3)
        steps = append(steps, step{name: k, function: v})
        return 0
    }}}, 0)
    lua.SetMetaTableNamed(l, "stepMetaTable")
    lua.LoadString(l, `step.request_tracking_js = function ()
    l.Call(0, 0)



Package Files

auxiliary.go base.go bit32.go code.go config.go debug.go doc.go dump.go instructions.go io.go libs.go load.go lua.go math.go os.go parser.go scanner.go stack.go string.go table.go tables.go tag_methods.go types.go undump.go unix.go vm.go


const (
    HookCall, MaskCall = iota, 1 << iota
    HookReturn, MaskReturn
    HookLine, MaskLine
    HookCount, MaskCount
    HookTailCall, MaskTailCall

Debug.Event and SetDebugHook mask argument values.

const (
    // RegistryIndex is the pseudo-index for the registry table.
    RegistryIndex = firstPseudoIndex

    // RegistryIndexMainThread is the registry index for the main thread of the
    // State. (The main thread is the one created together with the State.)
    RegistryIndexMainThread = iota

    // RegistryIndexGlobals is the registry index for the global environment.

Lua provides a registry, a predefined table, that can be used by any Go code to store whatever Lua values it needs to store. The registry table is always located at pseudo-index RegistryIndex, which is a valid index. Any Go library can store data into this table, but it should take care to choose keys that are different from those used by other libraries, to avoid collisions. Typically, you should use as key a string containing your library name, or a light userdata object in your code, or any Lua object created by your code. As with global names, string keys starting with an underscore followed by uppercase letters are reserved for Lua.

The integer keys in the registry are used by the reference mechanism and by some predefined values. Therefore, integer keys should not be used for other purposes.

When you create a new Lua state, its registry comes with some predefined values. These predefined values are indexed with integer keys defined as constants.

const (
    VersionMajor  = 5
    VersionMinor  = 2
    VersionNumber = 502
    VersionString = "Lua " + string('0'+VersionMajor) + "." + string('0'+VersionMinor)
const MinStack = 20

MinStack is the minimum Lua stack available to a Go function.

const MultipleReturns = -1

MultipleReturns is the argument for argCount or resultCount in ProtectedCall and Call.

const Signature = "\033Lua"

Signature is the mark for precompiled code ('<esc>Lua').


var (
    SyntaxError = errors.New("syntax error")
    MemoryError = errors.New("memory error")
    ErrorError  = errors.New("error within the error handler")
    FileError   = errors.New("file error")

Errors introduced by the Lua VM.

func ArgumentCheck Uses

func ArgumentCheck(l *State, cond bool, index int, extraMessage string)

ArgumentCheck checks whether cond is true. If not, raises an error with a standard message.

func ArgumentError Uses

func ArgumentError(l *State, argCount int, extraMessage string)

ArgumentError raises an error with a standard message that includes extraMessage as a comment.

This function never returns. It is an idiom to use it in Go functions as

lua.ArgumentError(l, args, "message")

func BaseOpen Uses

func BaseOpen(l *State) int

BaseOpen opens the basic library. Usually passed to Require.

func Bit32Open Uses

func Bit32Open(l *State) int

Bit32Open opens the bit32 library. Usually passed to Require.

func CallMeta Uses

func CallMeta(l *State, index int, event string) bool

CallMeta calls a metamethod.

If the object at index 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 there is no metatable or no metamethod, this function returns false (without pushing any value on the stack).

func CheckAny Uses

func CheckAny(l *State, index int)

CheckAny checks whether the function has an argument of any type (including nil) at position index.

func CheckInteger Uses

func CheckInteger(l *State, index int) int

func CheckNumber Uses

func CheckNumber(l *State, index int) float64

func CheckOption Uses

func CheckOption(l *State, index int, def string, list []string) int

func CheckStackWithMessage Uses

func CheckStackWithMessage(l *State, space int, message string)

func CheckString Uses

func CheckString(l *State, index int) string

CheckString checks whether the function argument at index is a string and returns this string.

This function uses ToString to get its result, so all conversions and caveats of that function apply here.

func CheckType Uses

func CheckType(l *State, index int, t Type)

CheckType checks whether the function argument at index has type t. See Type for the encoding of types for t.

func CheckUnsigned Uses

func CheckUnsigned(l *State, index int) uint

func CheckUserData Uses

func CheckUserData(l *State, index int, name string) interface{}

CheckUserData checks whether the function argument at index is a userdata of the type name (see NewMetaTable) and returns the userdata (see ToUserData).

func DebugHookCount Uses

func DebugHookCount(l *State) int

DebugHookCount returns the current hook count.

func DebugHookMask Uses

func DebugHookMask(l *State) byte

DebugHookMask returns the current hook mask.

func DebugOpen Uses

func DebugOpen(l *State) int

DebugOpen opens the debug library. Usually passed to Require.

func DoFile Uses

func DoFile(l *State, fileName string) error

DoFile loads and runs the given file.

func DoString Uses

func DoString(l *State, s string) error

DoString loads and runs the given string.

func Errorf Uses

func Errorf(l *State, format string, a ...interface{})

Errorf raises an error. The error message format is given by format plus any extra arguments, following the same rules as PushFString. It also adds at the beginning of the message the file name and the line number where the error occurred, if this information is available.

This function never returns. It is an idiom to use it in Go functions as:

lua.Errorf(l, args)

func FileResult Uses

func FileResult(l *State, err error, filename string) int

FileResult produces the return values for file-related functions in the standard library (io.open, os.rename, file:seek, etc.).

func IOOpen Uses

func IOOpen(l *State) int

IOOpen opens the io library. Usually passed to Require.

func LengthEx Uses

func LengthEx(l *State, index int) int

func LoadBuffer Uses

func LoadBuffer(l *State, b, name, mode string) error

func LoadFile Uses

func LoadFile(l *State, fileName, mode string) error

func LoadString Uses

func LoadString(l *State, s string) error

func MathOpen Uses

func MathOpen(l *State) int

MathOpen opens the math library. Usually passed to Require.

func MetaField Uses

func MetaField(l *State, index int, event string) bool

MetaField pushes onto the stack the field event from the metatable of the object at index. If the object does not have a metatable, or if the metatable does not have this field, returns false and pushes nothing.

func MetaTableNamed Uses

func MetaTableNamed(l *State, name string)

func NewLibrary Uses

func NewLibrary(l *State, functions []RegistryFunction)

func NewLibraryTable Uses

func NewLibraryTable(l *State, functions []RegistryFunction)

func NewMetaTable Uses

func NewMetaTable(l *State, name string) bool

NewMetaTable returns false if the registry already has the key name. Otherwise, creates a new table to be used as a metatable for userdata, adds it to the registry with key name, and returns true.

In both cases it pushes onto the stack the final value associated with name in the registry.

func OSOpen Uses

func OSOpen(l *State) int

OSOpen opens the os library. Usually passed to Require.

func OpenLibraries Uses

func OpenLibraries(l *State, preloaded ...RegistryFunction)

OpenLibraries opens all standard libraries. Alternatively, the host program can open them individually by using Require to call BaseOpen (for the basic library), PackageOpen (for the package library), CoroutineOpen (for the coroutine library), StringOpen (for the string library), TableOpen (for the table library), MathOpen (for the mathematical library), Bit32Open (for the bit library), IOOpen (for the I/O library), OSOpen (for the Operating System library), and DebugOpen (for the debug library).

The standard Lua libraries provide useful functions that are implemented directly through the Go API. Some of these functions provide essential services to the language (e.g. Type and MetaTable); others provide access to "outside" services (e.g. I/O); and others could be implemented in Lua itself, but are quite useful or have critical performance requirements that deserve an implementation in Go (e.g. table.sort).

All libraries are implemented through the official Go API. Currently, Lua has the following standard libraries:

basic library
package library
string manipulation
table manipulation
mathematical functions (sin, log, etc.);
bitwise operations
input and output
operating system facilities
debug facilities

Except for the basic and the package libraries, each library provides all its functions as fields of a global table or as methods of its objects.

func OptInteger Uses

func OptInteger(l *State, index, def int) int

func OptNumber Uses

func OptNumber(l *State, index int, def float64) float64

func OptString Uses

func OptString(l *State, index int, def string) string

OptString returns the string at index if it is a string. If this argument is absent or is nil, returns def. Otherwise, raises an error.

func OptUnsigned Uses

func OptUnsigned(l *State, index int, def uint) uint

func PackageOpen Uses

func PackageOpen(l *State) int

PackageOpen opens the package library. Usually passed to Require.

func Require Uses

func Require(l *State, name string, f Function, global bool)

Require calls function f with string name as an argument and sets the call result in package.loaded[name], as if that function had been called through require.

If global is true, also stores the result into global name.

Leaves a copy of that result on the stack.

func SetDebugHook Uses

func SetDebugHook(l *State, f Hook, mask byte, count int)

SetDebugHook sets the debugging hook function.

f is the hook function. mask specifies on which events the hook will be called: it is formed by a bitwise or of the constants MaskCall, MaskReturn, MaskLine, and MaskCount. The count argument is only meaningful when the mask includes MaskCount. For each event, the hook is called as explained below:

Call hook is called when the interpreter calls a function. The hook is called just after Lua enters the new function, before the function gets its arguments.

Return hook is called when the interpreter returns from a function. The hook is called just before Lua leaves the function. There is no standard way to access the values to be returned by the function.

Line hook is called when the interpreter is about to start the execution of a new line of code, or when it jumps back in the code (even to the same line). (This event only happens while Lua is executing a Lua function.)

Count hook is called after the interpreter executes every count instructions. (This event only happens while Lua is executing a Lua function.)

A hook is disabled by setting mask to zero.

func SetFunctions Uses

func SetFunctions(l *State, functions []RegistryFunction, upValueCount uint8)

func SetMetaTableNamed Uses

func SetMetaTableNamed(l *State, name string)

func SetUpValue Uses

func SetUpValue(l *State, function, index int) (name string, ok bool)

SetUpValue sets the value of a closure's upvalue. It assigns the value at the top of the stack to the upvalue and returns its name. It also pops a value from the stack. function and index are as in UpValue.

Returns an empty string and false if the index is greater than the number of upvalues.


func StringOpen Uses

func StringOpen(l *State) int

StringOpen opens the string library. Usually passed to Require.

func SubTable Uses

func SubTable(l *State, index int, name string) bool

func TableOpen Uses

func TableOpen(l *State) int

TableOpen opens the table library. Usually passed to Require.

func TestUserData Uses

func TestUserData(l *State, index int, name string) interface{}

func ToStringMeta Uses

func ToStringMeta(l *State, index int) (string, bool)

ToStringMeta converts any Lua value at the given index to a Go string in a reasonable format. The resulting string is pushed onto the stack and also returned by the function.

If the value has a metatable with a "__tostring" field, then ToStringMeta calls the corresponding metamethod with the value as argument, and uses the result of the call as its result.

func Traceback Uses

func Traceback(l, l1 *State, message string, level int)

Traceback creates and pushes a traceback of the stack l1. If message is not nil it is appended at the beginning of the traceback. The level parameter tells at which level to start the traceback.

func TypeNameOf Uses

func TypeNameOf(l *State, index int) string

func UpValue Uses

func UpValue(l *State, function, index int) (name string, ok bool)

UpValue returns the name of the upvalue at index away from function, where index cannot be greater than the number of upvalues.

Returns an empty string and false if the index is greater than the number of upvalues.

func UpValueId Uses

func UpValueId(l *State, f, n int) interface{}

UpValueId returns a unique identifier for the upvalue numbered n from the closure at index f. Parameters f and n are as in UpValue (but n cannot be greater than the number of upvalues).

These unique identifiers allow a program to check whether different closures share upvalues. Lua closures that share an upvalue (that is, that access a same external local variable) will return identical ids for those upvalue indices.

func UpValueIndex Uses

func UpValueIndex(i int) int

UpValueIndex returns the pseudo-index that represents the i-th upvalue of the running function.


func UpValueJoin Uses

func UpValueJoin(l *State, f1, n1, f2, n2 int)

UpValueJoin makes the n1-th upvalue of the Lua closure at index f1 refer to the n2-th upvalue of the Lua closure at index f2.

func Version Uses

func Version(l *State) *float64

Version returns the address of the version number stored in the Lua core.


func Where Uses

func Where(l *State, level int)

Where pushes onto the stack a string identifying the current position of the control at level in the call stack. Typically this string has the following format:


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.

type ComparisonOperator Uses

type ComparisonOperator int

A ComparisonOperator is an op argument for Compare.

const (
    OpEq ComparisonOperator = iota // Compares for equality (==).
    OpLT                           // Compares for less than (<).
    OpLE                           // Compares for less or equal (<=).

Valid ComparisonOperator values for Compare.

type Debug Uses

type Debug struct {
    Event int

    // 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 function checks how the function was
    // called to find a suitable name. If it cannot find a name, then Name is "".
    Name string

    // NameKind explains the name field. The value of NameKind 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.)
    NameKind 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. 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 describe 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

    // UpValueCount is the number of upvalues of the function.
    UpValueCount int

    // ParameterCount is the number of fixed parameters of the function (always 0
    // for Go functions).
    ParameterCount int

    // IsVarArg is true if the function is a vararg 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
    // contains filtered or unexported fields

A Debug carries different pieces of information about a function or an activation record. Stack fills only the private part of this structure, for later use. To fill the other fields of a Debug with useful information, call Info.

func Info Uses

func Info(l *State, what string, where Frame) (d Debug, ok bool)

Info gets information about a specific function or function invocation.

To get information about a function invocation, the parameter where must be a valid activation record that was filled by a previous call to Stack or given as an argument to a hook (see Hook).

To get information about a function you push it onto the stack and start the what string with the character '>'. (In that case, Info pops the function from the top of the stack.) For instance, to know in which line a function f was defined, you can write the following code:

l.Global("f") // Get global 'f'.
d, _ := lua.Info(l, ">S", nil)
fmt.Printf("%d\n", d.LineDefined)

Each character in the string what selects some fields of the Debug struct to be filled or a value to be pushed on the stack:

'n': fills in the field Name and NameKind
'S': fills in the fields Source, ShortSource, LineDefined, LastLineDefined, and What
'l': fills in the field CurrentLine
't': fills in the field IsTailCall
'u': fills in the fields UpValueCount, ParameterCount, and IsVarArg
'f': pushes onto the stack the function that is running at the given level
'L': pushes onto the stack a table whose indices are the numbers of the lines that are valid on the function

(A valid line is a line with some associated code, that is, a line where you can put a break point. Non-valid lines include empty lines and comments.)

This function returns false on error (for instance, an invalid option in what).

type Frame Uses

type Frame *callInfo

A Frame is a token representing an activation record. It is returned by Stack and passed to Info.

func Stack Uses

func Stack(l *State, level int) (f Frame, ok bool)

Stack gets information about the interpreter runtime stack.

It returns a Frame identifying the activation record of the function executing at a 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 on the stack). When there are no errors, Stack returns true; when called with a level greater than the stack depth, it returns false.

type Function Uses

type Function func(state *State) int

A Function is a Go function intended to be called from Lua.

This example receives a variable number of numerical arguments and returns their average and sum.


n := l.Top() // Number of arguments.
var sum float64
for i := 1; i <= n; i++ {
    f, ok := l.ToNumber(i)
    if !ok {
        l.PushString("incorrect argument")
    sum += f
l.PushNumber(sum / float64(n)) // First result.
l.PushNumber(sum)              // Second result.
return 2                       // Result count.

func AtPanic Uses

func AtPanic(l *State, panicFunction Function) Function

AtPanic sets a new panic function and returns the old one.

type Hook Uses

type Hook func(state *State, activationRecord Debug)

A Hook is a callback function that can be registered with SetDebugHook to trace various VM events.

func DebugHook Uses

func DebugHook(l *State) Hook

DebugHook returns the current hook function.

type Operator Uses

type Operator int

An Operator is an op argument for Arith.

const (
    OpAdd        Operator = iota // Performs addition (+).
    OpSub                        // Performs subtraction (-).
    OpMul                        // Performs multiplication (*).
    OpDiv                        // Performs division (/).
    OpMod                        // Performs modulo (%).
    OpPow                        // Performs exponentiation (^).
    OpUnaryMinus                 // Performs mathematical negation (unary -).

Valid Operator values for Arith.

type RegistryFunction Uses

type RegistryFunction struct {
    Name     string
    Function Function

A RegistryFunction is used for arrays of functions to be registered by SetFunctions. Name is the function name and Function is the function.

type RuntimeError Uses

type RuntimeError string

A RuntimeError is an error raised internally by the Lua VM or through Error.

func (RuntimeError) Error Uses

func (r RuntimeError) Error() string

type State Uses

type State struct {
    // contains filtered or unexported fields

A State is an opaque structure representing per thread Lua state.

func NewState Uses

func NewState() *State

NewState creates a new thread running in a new, independent state.


func NewStateEx Uses

func NewStateEx() *State

NewStateEx creates a new Lua state. It calls NewState and then sets a panic function that prints an error message to the standard error output in case of fatal errors.

Returns the new state.

func (*State) AbsIndex Uses

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

AbsIndex converts the acceptable index index to an absolute index (that is, one that does not depend on the stack top).


func (*State) Arith Uses

func (l *State) Arith(op Operator)

Arith performs an arithmetic operation over the two values (or one, in case of negation) at the top of the stack, with the value at the top being the second operand, ops 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).


func (*State) Call Uses

func (l *State) Call(argCount, resultCount int)

Call calls a function. To do so, use the following protocol: first, the function to be called is pushed onto the stack; then, the arguments to the function are pushed in direct order - that is, the first argument is pushed first. Finally, call Call. argCount is the number of arguments that you pushed onto the stack. All arguments and the function value are popped from the stack when the function is called.

The results are pushed onto the stack when the function returns. The number of results is adjusted to resultCount, unless resultCount is MultipleReturns. In this case, all results from the function are pushed. Lua takes care that the returned values fit into the stack space. 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.

Any error inside the called function provokes a call to panic().

The following example shows how the host program can do the equivalent to this Lua code:

a = f("how", t.x, 14)

Here it is in Go:

l.Global("f")       // Function to be called.
l.PushString("how") // 1st argument.
l.Global("t")       // Table to be indexed.
l.Field(-1, "x")    // Push result of t.x (2nd arg).
l.Remove(-2)        // Remove t from the stack.
l.PushInteger(14)   // 3rd argument.
l.Call(3, 1)        // Call f with 3 arguments and 1 result.
l.SetGlobal("a")    // Set global a.

Note that the code above is "balanced": at its end, the stack is back to its original configuration. This is considered good programming practice.


func (*State) CallWithContinuation Uses

func (l *State) CallWithContinuation(argCount, resultCount, context int, continuation Function)

CallWithContinuation is exactly like Call, but allows the called function to yield.


func (*State) CheckStack Uses

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

CheckStack ensures that there are at least size free stack slots in the stack. This call will not panic(), unlike the other Check*() functions.


func (*State) Compare Uses

func (l *State) Compare(index1, index2 int, op ComparisonOperator) bool

Compare compares two values.


func (*State) Concat Uses

func (l *State) Concat(n int)

Concat concatenates the n values at the top of the stack, pops them, and leaves the result at 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 semantic of Lua.


func (*State) Context Uses

func (l *State) Context() (int, bool, error)

Context is called by a continuation function to retrieve the status of the thread and context information. When called in the origin function, it will always return (0, false, nil). When called inside a continuation function, it will return (ctx, shouldYield, err), where ctx is the value that was passed to the callee together with the continuation function.


func (*State) Copy Uses

func (l *State) Copy(from, to int)

Copy moves the element at the index from into the valid index to without shifting any element (therefore replacing the value at that position).


func (*State) CreateTable Uses

func (l *State) CreateTable(arrayCount, recordCount int)

CreateTable creates a new empty table and pushes it onto the stack. arrayCount is a hint for how many elements the table will have as a sequence; recordCount is a hint for how many other elements the table will have. Lua may use these hints to preallocate memory for the the new table. This pre-allocation is useful for performance when you know in advance how many elements the table will have. Otherwise, you can use the function NewTable.


func (*State) Dump Uses

func (l *State) Dump(w io.Writer) error

Dump dumps a function as a binary chunk. It 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.


func (*State) Error Uses

func (l *State) Error()

Error generates a Lua error. The error message must be on the stack top. The error can be any of any Lua type. This function will panic().


func (*State) Field Uses

func (l *State) Field(index int, name string)

Field pushes onto the stack the value table[name], where table is the table on the stack at the given index. This call may trigger a metamethod for the __index event.


func (*State) Global Uses

func (l *State) Global(name string)

Global pushes onto the stack the value of the global name.


func (*State) Insert Uses

func (l *State) Insert(index int)

Insert moves the top element into the given valid index, shifting up the elements above this index to open space. This function cannot be called with a pseudo-index, because a pseudo-index is not an actual stack position.


func (*State) IsBoolean Uses

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

IsBoolean verifies that the value at index is a boolean.


func (*State) IsFunction Uses

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

IsFunction verifies that the value at index is a function, either Go or Lua function.


func (*State) IsGoFunction Uses

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

IsGoFunction verifies that the value at index is a Go function.


func (*State) IsLightUserData Uses

func (l *State) IsLightUserData(index int) bool

IsLightUserData verifies that the value at index is a light userdata.


func (*State) IsNil Uses

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

IsNil verifies that the value at index is nil.


func (*State) IsNone Uses

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

IsNone verifies that the value at index is not valid.


func (*State) IsNoneOrNil Uses

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

IsNoneOrNil verifies that the value at index is either nil or invalid.


func (*State) IsNumber Uses

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

IsNumber verifies that the value at index is a number.


func (*State) IsString Uses

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

IsString verifies that the value at index is a string, or a number (which is always convertible to a string).


func (*State) IsTable Uses

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

IsTable verifies that the value at index is a table.


func (*State) IsThread Uses

func (l *State) IsThread(index int) bool

IsThread verifies that the value at index is a thread.


func (*State) IsUserData Uses

func (l *State) IsUserData(index int) bool

IsUserData verifies that the value at index is a userdata.


func (*State) Length Uses

func (l *State) Length(index int)

Length of the value at index; it is equivalent to the # operator in Lua. The result is pushed on the stack.


func (*State) Load Uses

func (l *State) Load(r io.Reader, chunkName string, mode string) error

Load loads a Lua chunk, without running it. If there are no errors, it pushes the compiled chunk as a Lua function on top of the stack. Otherwise, it pushes an error message.


func (*State) MetaTable Uses

func (l *State) MetaTable(index int) bool

MetaTable pushes onto the stack the metatable of the value at index. If the value at index does not have a metatable, the function returns false and nothing is put onto the stack.


func (*State) NewTable Uses

func (l *State) NewTable()

NewTable creates a new empty table and pushes it onto the stack. It is equivalent to l.CreateTable(0, 0).


func (*State) Next Uses

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

Next pops a key from the stack and pushes a key-value pair from the table at index, while the table has next elements. If there are no more elements, nothing is pushed on the stack and Next returns false.

A typical traversal looks like this:

// Table is on top of the stack (index -1).
l.PushNil() // Add nil entry on stack (need 2 free slots).
for l.Next(-2) {
	key := lua.CheckString(l, -2)
	val := lua.CheckString(l, -1)
	l.Pop(1) // Remove val, but need key for the next iter.


func (*State) Pop Uses

func (l *State) Pop(n int)

Pop pops n elements from the stack.


func (*State) ProtectedCall Uses

func (l *State) ProtectedCall(argCount, resultCount, errorFunction int) error

ProtectedCall calls a function in protected mode. Both argCount and resultCount have the same meaning as in Call. If there are no errors during the call, ProtectedCall behaves exactly like Call.

However, if there is any error, ProtectedCall catches it, pushes a single value on the stack (the error message), and returns an error. Like Call, ProtectedCall always removes the function and its arguments from the stack.

If errorFunction is 0, then the error message returned on the stack is exactly the original error message. Otherwise, errorFunction is the stack index of an error handler (in the Lua C, message handler). This cannot be a pseudo-index in the current implementation. In case of runtime errors, this function will be called with the error message and its return value will be the message returned on the stack by ProtectedCall.

Typically, the error handler is used to add more debug information to the error message, such as a stack traceback. Such information cannot be gathered after the return of ProtectedCall, since by then, the stack has unwound.

The possible errors are the following:

RuntimeError  a runtime error
MemoryError   allocating memory, the error handler is not called
ErrorError    running the error handler


func (*State) ProtectedCallWithContinuation Uses

func (l *State) ProtectedCallWithContinuation(argCount, resultCount, errorFunction, context int, continuation Function) (err error)

ProtectedCallWithContinuation behaves exactly like ProtectedCall, but allows the called function to yield.


func (*State) PushBoolean Uses

func (l *State) PushBoolean(b bool)

PushBoolean pushes a boolean value with value b onto the stack.


func (*State) PushFString Uses

func (l *State) PushFString(format string, args ...interface{}) string

PushFString pushes onto the stack a formatted string and returns that string. It is similar to fmt.Sprintf, but has some differences: the conversion specifiers are quite restricted. There are no flags, widths, or precisions. The conversion specifiers can only be %% (inserts a % in the string), %s, %f (a Lua number), %p (a pointer as a hexadecimal numeral), %d and %c (an integer as a byte).


func (*State) PushGlobalTable Uses

func (l *State) PushGlobalTable()

PushGlobalTable pushes the global environment onto the stack.


func (*State) PushGoClosure Uses

func (l *State) PushGoClosure(function Function, upValueCount uint8)

PushGoClosure pushes a new Go closure onto the stack.

When a Go function is created, it is possible to associate some values with it, thus creating a Go closure; these values are then accessible to the function whenever it is called. To associate values with a Go function, first these values should be pushed onto the stack (when there are multiple values, the first value is pushed first). Then PushGoClosure is called to create and push the Go function onto the stack, with the argument upValueCount telling how many values should be associated with the function. Calling PushGoClosure also pops these values from the stack.

When upValueCount is 0, this function creates a light Go function, which is just a Go function.


func (*State) PushGoFunction Uses

func (l *State) PushGoFunction(f Function)

PushGoFunction pushes a Function implemented in Go onto the stack.


func (*State) PushInteger Uses

func (l *State) PushInteger(n int)

PushInteger pushes n onto the stack.


func (*State) PushLightUserData Uses

func (l *State) PushLightUserData(d interface{})

PushLightUserData pushes a light user data onto the stack. Userdata represents Go values in Lua. A light userdata is an interface{}. Its equality matches the Go rules (http://golang.org/ref/spec#Comparison_operators).


func (*State) PushNil Uses

func (l *State) PushNil()

PushNil pushes a nil value onto the stack.


func (*State) PushNumber Uses

func (l *State) PushNumber(n float64)

PushNumber pushes a number onto the stack.


func (*State) PushString Uses

func (l *State) PushString(s string) string

PushString pushes a string onto the stack.


func (*State) PushThread Uses

func (l *State) PushThread() bool

PushThread pushes the thread l onto the stack. It returns true if l is the main thread of its state.


func (*State) PushUnsigned Uses

func (l *State) PushUnsigned(n uint)

PushUnsigned pushes n onto the stack.


func (*State) PushUserData Uses

func (l *State) PushUserData(d interface{})

PushUserData is similar to PushLightUserData, but pushes a full userdata onto the stack.

func (*State) PushValue Uses

func (l *State) PushValue(index int)

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


func (*State) RawEqual Uses

func (l *State) RawEqual(index1, index2 int) bool

RawEqual verifies that the values at index1 and index2 are primitively equal (that is, without calling their metamethods).


func (*State) RawGet Uses

func (l *State) RawGet(index int)

RawGet is similar to GetTable, but does a raw access (without metamethods).


func (*State) RawGetInt Uses

func (l *State) RawGetInt(index, key int)

RawGetInt pushes onto the stack the value table[key] where table is the value at index on the stack. The access is raw, as it doesn't invoke metamethods.


func (*State) RawGetValue Uses

func (l *State) RawGetValue(index int, p interface{})

RawGetValue pushes onto the stack value table[p] where table is the value at index on the stack, and p is a light userdata. The access is raw, as it doesn't invoke metamethods.


func (*State) RawLength Uses

func (l *State) RawLength(index int) int

RawLength returns the length of the value at index. For strings, this is the length. For tables, this is the result of the # operator with no metamethods. For userdata, this is the size of the block of memory allocated for the userdata (not implemented yet). For other values, it is 0.


func (*State) RawSet Uses

func (l *State) RawSet(index int)

RawSet is similar to SetTable, but does a raw assignment (without metamethods).


func (*State) RawSetInt Uses

func (l *State) RawSetInt(index, key int)

RawSetInt does the equivalent of table[n]=v where table is the table at index and v is the value at the top of the stack.

This function pops the value from the stack. The assignment is raw; it doesn't invoke metamethods.


func (*State) Register Uses

func (l *State) Register(name string, f Function)

Register sets the Go function f as the new value of global name. If name was already defined, it is overwritten.


func (*State) Remove Uses

func (l *State) Remove(index int)

Remove the element at the given valid index, shifting down the elements above 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 Uses

func (l *State) Replace(index int)

Replace moves the top element into the given valid index without shifting any element (therefore replacing the value at the given index), and then pops the top element.


func (*State) SetField Uses

func (l *State) SetField(index int, key string)

SetField does the equivalent of table[key]=v where table is the value at index and v is the value on top of the stack.

This function pops the value from the stack. As in Lua, this function may trigger a metamethod for the __newindex event.


func (*State) SetGlobal Uses

func (l *State) SetGlobal(name string)

SetGlobal pops a value from the stack and sets it as the new value of global name.


func (*State) SetMetaTable Uses

func (l *State) SetMetaTable(index int)

SetMetaTable pops a table from the stack and sets it as the new metatable for the value at index.


func (*State) SetTable Uses

func (l *State) SetTable(index int)

SetTable does the equivalent of table[key]=v, where table is the value at index, v is the value at the top of the stack and key is the value just below the top.

The 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 Uses

func (l *State) SetTop(index int)

SetTop accepts any index, or 0, and sets the stack top to index. If the new top is larger than the old one, then the new elements are filled with nil. If index is 0, then all stack elements are removed.

If index is negative, the stack will be decremented by that much. If the decrement is larger than the stack, SetTop will panic().


func (*State) SetUserValue Uses

func (l *State) SetUserValue(index int)

SetUserValue pops a table or nil from the stack and sets it as the new value associated to the userdata at index.


func (*State) Table Uses

func (l *State) Table(index int)

Table pushes onto the stack the value table[top], where table is the value at index, and top is the value at the top of the stack. This function pops the key from the stack, putting the resulting value in its place. As in Lua, this function may trigger a metamethod for the __index event.


func (*State) ToBoolean Uses

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

ToBoolean converts the Lua value at index to a Go boolean. Like all tests in Lua, the only false values are false booleans and nil. Otherwise, all other Lua values evaluate to true.

To accept only actual boolean values, use the test IsBoolean.


func (*State) ToGoFunction Uses

func (l *State) ToGoFunction(index int) Function

ToGoFunction converts a value at index into a Go function. That value must be a Go function, otherwise it returns nil.


func (*State) ToInteger Uses

func (l *State) ToInteger(index int) (int, bool)

ToInteger converts the Lua value at index into a signed integer. The Lua value must be a number, or a string convertible to a number.

If the number is not an integer, it is truncated in some non-specified way.

If the operation failed, the second return value will be false.


func (*State) ToNumber Uses

func (l *State) ToNumber(index int) (float64, bool)

ToNumber converts the Lua value at index to the Go type for a Lua number (float64). The Lua value must be a number or a string convertible to a number.

If the operation failed, the second return value will be false.


func (*State) ToString Uses

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

ToString converts the Lua value at index to a Go string. The Lua value must also be a string or a number; otherwise the function returns false for its second return value.


func (*State) ToThread Uses

func (l *State) ToThread(index int) *State

ToThread converts the value at index to a Lua thread (a State). This value must be a thread, otherwise the return value will be nil.


func (*State) ToUnsigned Uses

func (l *State) ToUnsigned(index int) (uint, bool)

ToUnsigned converts the Lua value at index to a Go uint. The Lua value must be a number or a string convertible to a number.

If the number is not an unsigned integer, it is truncated in some non-specified way. If the number is outside the range of uint, it is normalized to the remainder of its division by one more than the maximum representable value.

If the operation failed, the second return value will be false.


func (*State) ToUserData Uses

func (l *State) ToUserData(index int) interface{}

ToUserData returns an interface{} of the userdata of the value at index. Otherwise, it returns nil.


func (*State) ToValue Uses

func (l *State) ToValue(index int) interface{}

ToValue convertes the value at index into a generic Go interface{}. The value can be a userdata, a table, a thread, a function, or Go string, bool or float64 types. Otherwise, the function returns nil.

Different objects will give different values. There is no way to convert the value back into its original value.

Typically, this function is used only for debug information.


func (*State) Top Uses

func (l *State) Top() int

Top returns the index of the top element in the stack. Because Lua indices start at 1, this result is equal to the number of elements in the stack (hence 0 means an empty stack).


func (*State) TypeOf Uses

func (l *State) TypeOf(index int) Type

TypeOf returns the type of the value at index, or TypeNone for a non-valid (but acceptable) index.


func (*State) UserValue Uses

func (l *State) UserValue(index int)

UserValue pushes onto the stack the Lua value associated with the userdata at index. This value must be a table or nil.


type Type Uses

type Type int

A Type is a symbolic representation of a Lua VM type.

const (
    TypeNil Type = iota

    TypeNone = TypeNil - 1

Valid Type values.

func (Type) String Uses

func (t Type) String() string

String returns the name of Type t.


Package lua imports 22 packages (graph) and is imported by 64 packages. Updated 2019-11-14. Refresh now. Tools for package owners.