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 ¶
- Constants
- Variables
- func ArgumentCheck(l *State, cond bool, index int, extraMessage string)
- func ArgumentError(l *State, argCount int, extraMessage string)
- func BaseOpen(l *State) int
- func Bit32Open(l *State) int
- func CallMeta(l *State, index int, event string) bool
- func CheckAny(l *State, index int)
- func CheckInteger(l *State, index int) int
- func CheckNumber(l *State, index int) float64
- func CheckOption(l *State, index int, def string, list []string) int
- func CheckStackWithMessage(l *State, space int, message string)
- func CheckString(l *State, index int) string
- func CheckType(l *State, index int, t Type)
- func CheckUnsigned(l *State, index int) uint
- func CheckUserData(l *State, index int, name string) interface{}
- func DebugHookCount(l *State) int
- func DebugHookMask(l *State) byte
- func DebugOpen(l *State) int
- func DoFile(l *State, fileName string) error
- func DoString(l *State, s string) error
- func Errorf(l *State, format string, a ...interface{})
- func FileResult(l *State, err error, filename string) int
- func IOOpen(l *State) int
- func LengthEx(l *State, index int) int
- func LoadBuffer(l *State, b, name, mode string) error
- func LoadFile(l *State, fileName, mode string) error
- func LoadString(l *State, s string) error
- func MathOpen(l *State) int
- func MetaField(l *State, index int, event string) bool
- func MetaTableNamed(l *State, name string)
- func NewLibrary(l *State, functions []RegistryFunction)
- func NewLibraryTable(l *State, functions []RegistryFunction)
- func NewMetaTable(l *State, name string) bool
- func OSOpen(l *State) int
- func OpenLibraries(l *State, preloaded ...RegistryFunction)
- func OptInteger(l *State, index, def int) int
- func OptNumber(l *State, index int, def float64) float64
- func OptString(l *State, index int, def string) string
- func OptUnsigned(l *State, index int, def uint) uint
- func PackageOpen(l *State) int
- func Require(l *State, name string, f Function, global bool)
- func SetDebugHook(l *State, f Hook, mask byte, count int)
- func SetFunctions(l *State, functions []RegistryFunction, upValueCount uint8)
- func SetMetaTableNamed(l *State, name string)
- func SetUpValue(l *State, function, index int) (name string, ok bool)
- func StringOpen(l *State) int
- func SubTable(l *State, index int, name string) bool
- func TableOpen(l *State) int
- func TestUserData(l *State, index int, name string) interface{}
- func ToStringMeta(l *State, index int) (string, bool)
- func Traceback(l, l1 *State, message string, level int)
- func TypeNameOf(l *State, index int) string
- func UpValue(l *State, function, index int) (name string, ok bool)
- func UpValueId(l *State, f, n int) interface{}
- func UpValueIndex(i int) int
- func UpValueJoin(l *State, f1, n1, f2, n2 int)
- func Version(l *State) *float64
- func Where(l *State, level int)
- type ComparisonOperator
- type Debug
- type Frame
- type Function
- type Hook
- type Operator
- type RegistryFunction
- type RuntimeError
- type State
- func (l *State) AbsIndex(index int) int
- func (l *State) Arith(op Operator)
- func (l *State) Call(argCount, resultCount int)
- func (l *State) CallWithContinuation(argCount, resultCount, context int, continuation Function)
- func (l *State) CheckStack(size int) bool
- func (l *State) Compare(index1, index2 int, op ComparisonOperator) bool
- func (l *State) Concat(n int)
- func (l *State) Context() (int, bool, error)
- func (l *State) Copy(from, to int)
- func (l *State) CreateTable(arrayCount, recordCount int)
- func (l *State) Dump(w io.Writer) error
- func (l *State) Error()
- func (l *State) Field(index int, name string)
- func (l *State) Global(name string)
- func (l *State) Insert(index int)
- func (l *State) IsBoolean(index int) bool
- func (l *State) IsFunction(index int) bool
- func (l *State) IsGoFunction(index int) bool
- func (l *State) IsLightUserData(index int) bool
- func (l *State) IsNil(index int) bool
- func (l *State) IsNone(index int) bool
- func (l *State) IsNoneOrNil(index int) bool
- func (l *State) IsNumber(index int) bool
- func (l *State) IsString(index int) bool
- func (l *State) IsTable(index int) bool
- func (l *State) IsThread(index int) bool
- func (l *State) IsUserData(index int) bool
- func (l *State) Length(index int)
- func (l *State) Load(r io.Reader, chunkName string, mode string) error
- func (l *State) MetaTable(index int) bool
- func (l *State) NewTable()
- func (l *State) Next(index int) bool
- func (l *State) Pop(n int)
- func (l *State) ProtectedCall(argCount, resultCount, errorFunction int) error
- func (l *State) ProtectedCallWithContinuation(argCount, resultCount, errorFunction, context int, continuation Function) (err error)
- func (l *State) PushBoolean(b bool)
- func (l *State) PushFString(format string, args ...interface{}) string
- func (l *State) PushGlobalTable()
- func (l *State) PushGoClosure(function Function, upValueCount uint8)
- func (l *State) PushGoFunction(f Function)
- func (l *State) PushInteger(n int)
- func (l *State) PushLightUserData(d interface{})
- func (l *State) PushNil()
- func (l *State) PushNumber(n float64)
- func (l *State) PushString(s string) string
- func (l *State) PushThread() bool
- func (l *State) PushUnsigned(n uint)
- func (l *State) PushUserData(d interface{})
- func (l *State) PushValue(index int)
- func (l *State) RawEqual(index1, index2 int) bool
- func (l *State) RawGet(index int)
- func (l *State) RawGetInt(index, key int)
- func (l *State) RawGetValue(index int, p interface{})
- func (l *State) RawLength(index int) int
- func (l *State) RawSet(index int)
- func (l *State) RawSetInt(index, key int)
- func (l *State) Register(name string, f Function)
- func (l *State) Remove(index int)
- func (l *State) Replace(index int)
- func (l *State) SetField(index int, key string)
- func (l *State) SetGlobal(name string)
- func (l *State) SetMetaTable(index int)
- func (l *State) SetTable(index int)
- func (l *State) SetTop(index int)
- func (l *State) SetUserValue(index int)
- func (l *State) Table(index int)
- func (l *State) ToBoolean(index int) bool
- func (l *State) ToGoFunction(index int) Function
- func (l *State) ToInteger(index int) (int, bool)
- func (l *State) ToNumber(index int) (float64, bool)
- func (l *State) ToString(index int) (s string, ok bool)
- func (l *State) ToThread(index int) *State
- func (l *State) ToUnsigned(index int) (uint, bool)
- func (l *State) ToUserData(index int) interface{}
- func (l *State) ToValue(index int) interface{}
- func (l *State) Top() int
- func (l *State) TypeOf(index int) Type
- func (l *State) UserValue(index int)
- type Type
Examples ¶
Constants ¶
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. 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.
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').
Variables ¶
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 ¶
ArgumentCheck checks whether cond is true. If not, raises an error with a standard message.
func ArgumentError ¶
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 CallMeta ¶
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 ¶
CheckAny checks whether the function has an argument of any type (including nil) at position index.
func CheckInteger ¶
func CheckNumber ¶
func CheckStackWithMessage ¶
func CheckString ¶
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 ¶
CheckType checks whether the function argument at index has type t. See Type for the encoding of types for t.
func CheckUnsigned ¶
func CheckUserData ¶
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 ¶
DebugHookCount returns the current hook count.
func Errorf ¶
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 ¶
FileResult produces the return values for file-related functions in the standard library (io.open, os.rename, file:seek, etc.).
func LoadBuffer ¶
func LoadString ¶
func MetaField ¶
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 NewLibrary ¶
func NewLibrary(l *State, functions []RegistryFunction)
func NewLibraryTable ¶
func NewLibraryTable(l *State, functions []RegistryFunction)
func NewMetaTable ¶
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 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 OptString ¶
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 PackageOpen ¶
PackageOpen opens the package library. Usually passed to Require.
func Require ¶
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 ¶
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 SetUpValue ¶
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 ¶
StringOpen opens the string library. Usually passed to Require.
func TestUserData ¶
func ToStringMeta ¶
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 ¶
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 UpValue ¶
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 ¶
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 ¶
UpValueIndex returns the pseudo-index that represents the i-th upvalue of the running function.
func UpValueJoin ¶
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 Where ¶
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 ¶
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 ¶
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 Hook ¶
A Hook is a callback function that can be registered with SetDebugHook to trace various VM events.
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 ¶
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.
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 ¶
AbsIndex converts the acceptable index index to an absolute index (that is, one that does not depend on the stack top).
func (*State) Arith ¶
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 ¶
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 ¶
CallWithContinuation is exactly like Call, but allows the called function to yield.
func (*State) CheckStack ¶
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 ¶
func (l *State) Compare(index1, index2 int, op ComparisonOperator) bool
Compare compares two values.
func (*State) Concat ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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) Insert ¶
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) IsFunction ¶
IsFunction verifies that the value at index is a function, either Go or Lua function.
func (*State) IsGoFunction ¶
IsGoFunction verifies that the value at index is a Go function.
func (*State) IsLightUserData ¶
IsLightUserData verifies that the value at index is a light userdata.
http://www.lua.org/manual/5.2/manual.html#lua_islightuserdata
func (*State) IsNoneOrNil ¶
IsNoneOrNil verifies that the value at index is either nil or invalid.
func (*State) IsString ¶
IsString verifies that the value at index is a string, or a number (which is always convertible to a string).
func (*State) IsUserData ¶
IsUserData verifies that the value at index is a userdata.
func (*State) Length ¶
Length of the value at index; it is equivalent to the # operator in Lua. The result is pushed on the stack.
func (*State) Load ¶
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 ¶
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 ¶
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 ¶
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) ProtectedCall ¶
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 ¶
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 ¶
PushBoolean pushes a boolean value with value b onto the stack.
func (*State) PushFString ¶
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 ¶
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 ¶
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 ¶
PushGoFunction pushes a Function implemented in Go onto the stack.
func (*State) PushInteger ¶
PushInteger pushes n onto the stack.
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) PushNumber ¶
PushNumber pushes a number onto the stack.
func (*State) PushString ¶
PushString pushes a string onto the stack.
func (*State) PushThread ¶
PushThread pushes the thread l onto the stack. It returns true if l is the main thread of its state.
func (*State) PushUnsigned ¶
PushUnsigned pushes n onto the stack.
func (*State) PushUserData ¶
func (l *State) PushUserData(d interface{})
PushUserData is similar to PushLightUserData, but pushes a full userdata onto the stack.
func (*State) RawEqual ¶
RawEqual verifies that the values at index1 and index2 are primitively equal (that is, without calling their metamethods).
func (*State) RawGetInt ¶
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 ¶
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 ¶
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 ¶
RawSet is similar to SetTable, but does a raw assignment (without metamethods).
func (*State) RawSetInt ¶
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 ¶
Register sets the Go function f as the new value of global name. If name was already defined, it is overwritten.
func (*State) Remove ¶
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 ¶
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 ¶
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 ¶
SetGlobal pops a value from the stack and sets it as the new value of global name.
func (*State) SetMetaTable ¶
SetMetaTable pops a table from the stack and sets it as the new metatable for the value at index.
func (*State) SetTable ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
ToGoFunction converts a value at index into a Go function. That value must be a Go function, otherwise it returns nil.
func (*State) ToInteger ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
ToUserData returns an interface{} of the userdata of the value at index. Otherwise, it returns nil.
func (*State) ToValue ¶
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 ¶
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 ¶
TypeOf returns the type of the value at index, or TypeNone for a non-valid (but acceptable) index.
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.