lua

package module
v0.0.0-...-5d657e3 Latest Latest
Warning

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

Go to latest
Published: Mar 12, 2024 License: MIT Imports: 22 Imported by: 148

README

Build Status GoDoc

A Lua VM in pure Go

go-lua is a port of the Lua 5.2 VM to pure Go. It is compatible with binary files dumped by luac, from the Lua reference implementation.

The motivation is to enable simple scripting of Go applications. For example, it is used to describe flows in Shopify's load generation tool, Genghis.

Usage

go-lua is intended to be used as a Go package. It does not include a command to run the interpreter. To start using the library, run:

go get github.com/Shopify/go-lua

To develop & test go-lua, you'll also need the lua-tests submodule checked out:

git submodule update --init

You can then develop with the usual Go commands, e.g.:

go build
go test -cover

A simple example that loads & runs a Lua script is:

package main

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

func main() {
  l := lua.NewState()
  lua.OpenLibraries(l)
  if err := lua.DoFile(l, "hello.lua"); err != nil {
    panic(err)
  }
}

Status

go-lua has been used in production in Shopify's load generation tool, Genghis, since May 2014, and is also part of Shopify's resiliency tooling.

The core VM and compiler has been ported and tested. The compiler is able to correctly process all Lua source files from the Lua test suite. The VM has been tested to correctly execute over a third of the Lua test cases.

Most core Lua libraries are at least partially implemented. Prominent exceptions are regular expressions, coroutines and string.dump.

Weak reference tables are not and will not be supported. go-lua uses the Go heap for Lua objects, and Go does not support weak references.

Benchmarks

Benchmark results shown here are taken from a Mid 2012 MacBook Pro Retina with a 2.6 GHz Core i7 CPU running OS X 10.10.2, go 1.4.2 and Lua 5.2.2.

The Fibonacci function can be written a few different ways to evaluate different performance characteristics of a language interpreter. The simplest way is as a recursive function:

  function fib(n)
    if n == 0 then
      return 0
    elseif n == 1 then
      return 1
    end
    return fib(n-1) + fib(n-2)
  end

This exercises the call stack implementation. When computing fib(35), go-lua is about 6x slower than the C Lua interpreter. Gopher-lua is about 20% faster than go-lua. Much of the performance difference between go-lua and gopher-lua comes from the inclusion of debug hooks in go-lua. The remainder is due to the call stack implementation - go-lua heap-allocates Lua stack frames with a separately allocated variant struct, as outlined above. Although it caches recently used stack frames, it is outperformed by the simpler statically allocated call stacks in gopher-lua.

  $ time lua fibr.lua
  real  0m2.807s
  user  0m2.795s
  sys   0m0.006s
  
  $ time glua fibr.lua
  real  0m14.528s
  user  0m14.513s
  sys   0m0.031s
  
  $ time go-lua fibr.lua
  real  0m17.411s
  user  0m17.514s
  sys   0m1.287s

The recursive Fibonacci function can be transformed into a tail-recursive variant:

  function fibt(n0, n1, c)
    if c == 0 then
      return n0
    else if c == 1 then
      return n1
    end
    return fibt(n1, n0+n1, c-1)
  end
  
  function fib(n)
    fibt(0, 1, n)
  end

The Lua interpreter detects and optimizes tail calls. This exhibits similar relative performance between the 3 interpreters, though gopher-lua edges ahead a little due to its simpler stack model and reduced bookkeeping.

  $ time lua fibt.lua
  real  0m0.099s
  user  0m0.096s
  sys   0m0.002s

  $ time glua fibt.lua
  real  0m0.489s
  user  0m0.484s
  sys   0m0.005s

  $ time go-lua fibt.lua
  real  0m0.607s
  user  0m0.610s
  sys   0m0.068s

Finally, we can write an explicitly iterative implementation:

  function fib(n)
    if n == 0 then
      return 0
    else if n == 1 then
      return 1
    end
    local n0, n1 = 0, 1
    for i = n, 2, -1 do
      local tmp = n0 + n1
      n0 = n1
      n1 = tmp
    end
    return n1
  end

This exercises more of the bytecode interpreter’s inner loop. Here we see the performance impact of Go’s switch implementation. Both go-lua and gopher-lua are an order of magnitude slower than the C Lua interpreter.

  $ time lua fibi.lua
  real  0m0.023s
  user  0m0.020s
  sys   0m0.003s

  $ time glua fibi.lua
  real  0m0.242s
  user  0m0.235s
  sys   0m0.005s

  $ time go-lua fibi.lua
  real  0m0.242s
  user  0m0.240s
  sys   0m0.028s

License

go-lua is licensed under the MIT license.

Documentation

Overview

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

Example
package main

import (
	"fmt"
	"github.com/Shopify/go-lua"
)

type step struct {
	name     string
	function interface{}
}

func main() {
	steps := []step{}
	l := lua.NewState()
	lua.BaseOpen(l)
	_ = 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)
	l.PushUserData(steps)
	l.PushValue(-1)
	l.SetGlobal("step")
	lua.SetMetaTableNamed(l, "stepMetaTable")
	lua.LoadString(l, `step.request_tracking_js = function ()
    get(config.domain..'/javascripts/shopify_stats.js')
  end`)
	l.Call(0, 0)
	fmt.Println(steps[0].name)
}
Output:

request_tracking_js

Index

Examples

Constants

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

Debug.Event and SetDebugHook mask argument values.

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

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.

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

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

View Source
const MultipleReturns = -1

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

View Source
const Signature = "\033Lua"

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

Variables

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

Functions

func ArgumentCheck

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

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")
panic("unreachable")

func BaseOpen

func BaseOpen(l *State) int

BaseOpen opens the basic library. Usually passed to Require.

func Bit32Open

func Bit32Open(l *State) int

Bit32Open opens the bit32 library. Usually passed to Require.

func CallMeta

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

func CheckAny(l *State, index int)

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

func CheckInteger

func CheckInteger(l *State, index int) int

func CheckNumber

func CheckNumber(l *State, index int) float64

func CheckOption

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

func CheckStackWithMessage

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

func CheckString

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

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

func CheckUnsigned(l *State, index int) uint

func CheckUserData

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

func DebugHookCount(l *State) int

DebugHookCount returns the current hook count.

func DebugHookMask

func DebugHookMask(l *State) byte

DebugHookMask returns the current hook mask.

func DebugOpen

func DebugOpen(l *State) int

DebugOpen opens the debug library. Usually passed to Require.

func DoFile

func DoFile(l *State, fileName string) error

DoFile loads and runs the given file.

func DoString

func DoString(l *State, s string) error

DoString loads and runs the given string.

func Errorf

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)
panic("unreachable")

func FileResult

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

func IOOpen(l *State) int

IOOpen opens the io library. Usually passed to Require.

func LengthEx

func LengthEx(l *State, index int) int

func LoadBuffer

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

func LoadFile

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

func LoadString

func LoadString(l *State, s string) error

func MathOpen

func MathOpen(l *State) int

MathOpen opens the math library. Usually passed to Require.

func MetaField

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

func MetaTableNamed(l *State, name string)

func NewLibrary

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

func NewLibraryTable

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

func NewMetaTable

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

func OSOpen(l *State) int

OSOpen opens the os library. Usually passed to Require.

func OpenLibraries

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

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

func OptNumber

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

func OptString

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

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

func PackageOpen

func PackageOpen(l *State) int

PackageOpen opens the package library. Usually passed to Require.

func Require

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

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

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

func SetMetaTableNamed

func SetMetaTableNamed(l *State, name string)

func SetUpValue

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.

http://www.lua.org/manual/5.2/manual.html#lua_setupvalue

func StringOpen

func StringOpen(l *State) int

StringOpen opens the string library. Usually passed to Require.

func SubTable

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

func TableOpen

func TableOpen(l *State) int

TableOpen opens the table library. Usually passed to Require.

func TestUserData

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

func ToStringMeta

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

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

func TypeNameOf(l *State, index int) string

func UpValue

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

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

func UpValueIndex(i int) int

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

http://www.lua.org/manual/5.2/manual.html#lua_upvalueindex

func UpValueJoin

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

func Version(l *State) *float64

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

http://www.lua.org/manual/5.2/manual.html#lua_version

func Where

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:

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 ComparisonOperator

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

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

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

type Frame *callInfo

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

func Stack

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

type Function func(state *State) int

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

func AtPanic

func AtPanic(l *State, panicFunction Function) Function

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

type Hook

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

func DebugHook(l *State) Hook

DebugHook returns the current hook function.

type Operator

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

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

type RuntimeError string

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

func (RuntimeError) Error

func (r RuntimeError) Error() string

type State

type State struct {
	// contains filtered or unexported fields
}

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

func NewState

func NewState() *State

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

http://www.lua.org/manual/5.2/manual.html#lua_newstate

func NewStateEx

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

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

http://www.lua.org/manual/5.2/manual.html#lua_absindex

func (*State) Arith

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

http://www.lua.org/manual/5.2/manual.html#lua_arith

func (*State) Call

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.

http://www.lua.org/manual/5.2/manual.html#lua_call

func (*State) CallWithContinuation

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

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

http://www.lua.org/manual/5.2/manual.html#lua_callk

func (*State) CheckStack

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.

http://www.lua.org/manual/5.2/manual.html#lua_checkstack

func (*State) Compare

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

Compare compares two values.

http://www.lua.org/manual/5.2/manual.html#lua_compare

func (*State) Concat

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.

http://www.lua.org/manual/5.2/manual.html#lua_concat

func (*State) Context

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.

http://www.lua.org/manual/5.2/manual.html#lua_getctx

func (*State) Copy

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

http://www.lua.org/manual/5.2/manual.html#lua_copy

func (*State) CreateTable

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.

http://www.lua.org/manual/5.2/manual.html#lua_createtable

func (*State) Dump

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.

http://www.lua.org/manual/5.3/manual.html#lua_dump

func (*State) Error

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().

http://www.lua.org/manual/5.2/manual.html#lua_error

func (*State) Field

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.

http://www.lua.org/manual/5.2/manual.html#lua_getfield

func (*State) Global

func (l *State) Global(name string)

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

http://www.lua.org/manual/5.2/manual.html#lua_getglobal

func (*State) Insert

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.

http://www.lua.org/manual/5.2/manual.html#lua_insert

func (*State) IsBoolean

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

IsBoolean verifies that the value at index is a boolean.

http://www.lua.org/manual/5.2/manual.html#lua_isboolean

func (*State) IsFunction

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

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

http://www.lua.org/manual/5.2/manual.html#lua_isfunction

func (*State) IsGoFunction

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

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

http://www.lua.org/manual/5.2/manual.html#lua_iscfunction

func (*State) IsLightUserData

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

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

http://www.lua.org/manual/5.2/manual.html#lua_islightuserdata

func (*State) IsNil

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

IsNil verifies that the value at index is nil.

http://www.lua.org/manual/5.2/manual.html#lua_isnil

func (*State) IsNone

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

IsNone verifies that the value at index is not valid.

http://www.lua.org/manual/5.2/manual.html#lua_isnone

func (*State) IsNoneOrNil

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

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

http://www.lua.org/manual/5.2/manual.html#lua_isnonornil.

func (*State) IsNumber

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

IsNumber verifies that the value at index is a number.

http://www.lua.org/manual/5.2/manual.html#lua_isnumber

func (*State) IsString

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

http://www.lua.org/manual/5.2/manual.html#lua_isstring

func (*State) IsTable

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

IsTable verifies that the value at index is a table.

http://www.lua.org/manual/5.2/manual.html#lua_istable

func (*State) IsThread

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

IsThread verifies that the value at index is a thread.

http://www.lua.org/manual/5.2/manual.html#lua_isthread

func (*State) IsUserData

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

IsUserData verifies that the value at index is a userdata.

http://www.lua.org/manual/5.2/manual.html#lua_isuserdata

func (*State) Length

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.

http://www.lua.org/manual/5.2/manual.html#lua_len

func (*State) Load

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.

http://www.lua.org/manual/5.2/manual.html#lua_load

func (*State) MetaTable

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.

http://www.lua.org/manual/5.2/manual.html#lua_getmetatable

func (*State) NewTable

func (l *State) NewTable()

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

http://www.lua.org/manual/5.2/manual.html#lua_newtable

func (*State) Next

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.
}

http://www.lua.org/manual/5.2/manual.html#lua_next

func (*State) Pop

func (l *State) Pop(n int)

Pop pops n elements from the stack.

http://www.lua.org/manual/5.2/manual.html#lua_pop

func (*State) ProtectedCall

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

http://www.lua.org/manual/5.2/manual.html#lua_pcall

func (*State) ProtectedCallWithContinuation

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.

http://www.lua.org/manual/5.2/manual.html#lua_pcallk

func (*State) PushBoolean

func (l *State) PushBoolean(b bool)

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

http://www.lua.org/manual/5.2/manual.html#lua_pushboolean

func (*State) PushFString

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

http://www.lua.org/manual/5.2/manual.html#lua_pushfstring

func (*State) PushGlobalTable

func (l *State) PushGlobalTable()

PushGlobalTable pushes the global environment onto the stack.

http://www.lua.org/manual/5.2/manual.html#lua_pushglobaltable

func (*State) PushGoClosure

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.

http://www.lua.org/manual/5.2/manual.html#lua_pushcclosure

func (*State) PushGoFunction

func (l *State) PushGoFunction(f Function)

PushGoFunction pushes a Function implemented in Go onto the stack.

http://www.lua.org/manual/5.2/manual.html#lua_pushcfunction

func (*State) PushInteger

func (l *State) PushInteger(n int)

PushInteger pushes n onto the stack.

http://www.lua.org/manual/5.2/manual.html#lua_pushinteger

func (*State) PushLightUserData

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

http://www.lua.org/manual/5.2/manual.html#lua_pushlightuserdata

func (*State) PushNil

func (l *State) PushNil()

PushNil pushes a nil value onto the stack.

http://www.lua.org/manual/5.2/manual.html#lua_pushnil

func (*State) PushNumber

func (l *State) PushNumber(n float64)

PushNumber pushes a number onto the stack.

http://www.lua.org/manual/5.2/manual.html#lua_pushnumber

func (*State) PushString

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

PushString pushes a string onto the stack.

http://www.lua.org/manual/5.2/manual.html#lua_pushstring

func (*State) PushThread

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.

http://www.lua.org/manual/5.2/manual.html#lua_pushthread

func (*State) PushUnsigned

func (l *State) PushUnsigned(n uint)

PushUnsigned pushes n onto the stack.

http://www.lua.org/manual/5.2/manual.html#lua_pushunsigned

func (*State) PushUserData

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

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

func (*State) PushValue

func (l *State) PushValue(index int)

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

http://www.lua.org/manual/5.2/manual.html#lua_pushvalue

func (*State) RawEqual

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

http://www.lua.org/manual/5.2/manual.html#lua_rawequal

func (*State) RawGet

func (l *State) RawGet(index int)

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

http://www.lua.org/manual/5.2/manual.html#lua_rawget

func (*State) RawGetInt

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.

http://www.lua.org/manual/5.2/manual.html#lua_rawgeti

func (*State) RawGetValue

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.

http://www.lua.org/manual/5.2/manual.html#lua_rawgetp

func (*State) RawLength

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.

http://www.lua.org/manual/5.2/manual.html#lua_rawlen

func (*State) RawSet

func (l *State) RawSet(index int)

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

http://www.lua.org/manual/5.2/manual.html#lua_rawset

func (*State) RawSetInt

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.

http://www.lua.org/manual/5.2/manual.html#lua_rawseti

func (*State) Register

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.

http://www.lua.org/manual/5.2/manual.html#lua_register

func (*State) Remove

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.

http://www.lua.org/manual/5.2/manual.html#lua_remove

func (*State) Replace

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.

http://www.lua.org/manual/5.2/manual.html#lua_replace

func (*State) SetField

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.

http://www.lua.org/manual/5.2/manual.html#lua_setfield

func (*State) SetGlobal

func (l *State) SetGlobal(name string)

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

http://www.lua.org/manual/5.2/manual.html#lua_setglobal

func (*State) SetMetaTable

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.

http://www.lua.org/manual/5.2/manual.html#lua_setmetatable

func (*State) SetTable

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.

http://www.lua.org/manual/5.2/manual.html#lua_settable

func (*State) SetTop

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().

http://www.lua.org/manual/5.2/manual.html#lua_settop

func (*State) SetUserValue

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.

http://www.lua.org/manual/5.2/manual.html#lua_setuservalue

func (*State) Table

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.

http://www.lua.org/manual/5.2/manual.html#lua_gettable

func (*State) ToBoolean

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.

http://www.lua.org/manual/5.2/manual.html#lua_toboolean

func (*State) ToGoFunction

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.

http://www.lua.org/manual/5.2/manual.html#lua_tocfunction

func (*State) ToInteger

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.

http://www.lua.org/manual/5.2/manual.html#lua_tointegerx

func (*State) ToNumber

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.

http://www.lua.org/manual/5.2/manual.html#lua_tonumberx

func (*State) ToString

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.

http://www.lua.org/manual/5.2/manual.html#lua_tolstring

func (*State) ToThread

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.

http://www.lua.org/manual/5.2/manual.html#lua_tothread

func (*State) ToUnsigned

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.

http://www.lua.org/manual/5.2/manual.html#lua_tounsignedx

func (*State) ToUserData

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

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

http://www.lua.org/manual/5.2/manual.html#lua_touserdata

func (*State) ToValue

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.

http://www.lua.org/manual/5.2/manual.html#lua_tovalue

func (*State) Top

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

http://www.lua.org/manual/5.2/manual.html#lua_gettop

func (*State) TypeOf

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.

http://www.lua.org/manual/5.2/manual.html#lua_type

func (*State) UserValue

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.

http://www.lua.org/manual/5.2/manual.html#lua_getuservalue

type Type

type Type int

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

const (
	TypeNil Type = iota
	TypeBoolean
	TypeLightUserData
	TypeNumber
	TypeString
	TypeTable
	TypeFunction
	TypeUserData
	TypeThread

	TypeCount
	TypeNone = TypeNil - 1
)

Valid Type values.

func (Type) String

func (t Type) String() string

String returns the name of Type t.

http://www.lua.org/manual/5.2/manual.html#lua_typename

Jump to

Keyboard shortcuts

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