api

package
v0.7.1 Latest Latest
Warning

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

Go to latest
Published: Apr 28, 2026 License: MIT Imports: 20 Imported by: 0

Documentation

Overview

Package api defines the public Go API for the Lua VM.

This is the Go equivalent of C's lua_* functions (lapi.c) and luaL_* auxiliary functions (lauxlib.c). It provides a stack-based API for manipulating Lua state from Go. All standard library implementations use this API.

Reference: .analysis/09-standard-libraries.md §1-§2

auxiliary.go — Auxiliary library functions (luaL_* equivalents).

call.go — Call and load operations (Call, PCall, Load, DoFile, DoString).

coroutine_impl.go — Coroutine API implementation (NewThread, Resume, Yield, Status).

debug_impl.go — Debug interface implementation (GetInfo, GetLocal, SetLocal, hooks).

gc_impl.go — GC integration (gcMarkSweep, GCCollect, clearStaleStack, finalizers).

impl.go — Core Lua API implementation (State, stack ops, push, type checks, conversions).

nodekey_init.go registers the ReconstructObj callback for table node key reconstruction. This breaks the import cycle: the table package can't import state/closure, but needs to return properly-typed TValues from nodeKey().

table_ops.go — Table access operations (GetTable, SetTable, GetField, SetField, Next, Len).

userdata_ops.go — Userdata and upvalue access operations.

Index

Constants

View Source
const (
	RIdxMainThread = 3 // LUA_RIDX_MAINTHREAD
	RIdxGlobals    = 2 // LUA_RIDX_GLOBALS — the _G table
)

Registry keys for well-known values.

View Source
const (
	StatusOK        = 0
	StatusYield     = 1
	StatusErrRun    = 2
	StatusErrSyntax = 3
	StatusErrMem    = 4
	StatusErrErr    = 5
	StatusErrFile   = 6 // file I/O error (mirrors LUA_ERRFILE)
)

Status codes

View Source
const MultiRet = -1

MultiRet signals "return all results".

View Source
const NoRef = -2

NoRef is the "no reference" value.

View Source
const RefNil = -1

RefNil is the reference value for nil.

View Source
const (
	RegistryIndex = -1000000 - 1000 // LUA_REGISTRYINDEX
)
View Source
const TypeNone object.Type = 0xFF

TypeNone is the type for invalid indices.

Variables

This section is empty.

Functions

func DebugGetProto

func DebugGetProto(L *State) *object.Proto

DebugGetProto returns the Proto of the LClosure at top of stack (for testing).

func UpvalueIndex

func UpvalueIndex(i int) int

UpvalueIndex returns the pseudo-index for upvalue i (1-based).

func WrapCFunction

func WrapCFunction(f CFunction) object.TValue

WrapCFunction wraps a CFunction into a state.CFunction + TValue. The caller can cache the result and pass it to PushCFunctionSame.

Types

type ArithOp

type ArithOp int

ArithOp is the arithmetic operation type.

const (
	OpAdd  ArithOp = 0
	OpSub  ArithOp = 1
	OpMul  ArithOp = 2
	OpMod  ArithOp = 3
	OpPow  ArithOp = 4
	OpDiv  ArithOp = 5
	OpIDiv ArithOp = 6
	OpBAnd ArithOp = 7
	OpBOr  ArithOp = 8
	OpBXor ArithOp = 9
	OpShl  ArithOp = 10
	OpShr  ArithOp = 11
	OpUnm  ArithOp = 12
	OpBNot ArithOp = 13
)

type CFunction

type CFunction func(L *State) int

CFunction is the type for Go functions callable from Lua. It receives the Lua state and returns the number of results pushed.

type CompareOp

type CompareOp int

CompareOp is the comparison operation type.

const (
	OpEQ CompareOp = 0 // ==
	OpLT CompareOp = 1 // <
	OpLE CompareOp = 2 // <=
)

type DebugInfo

type DebugInfo struct {
	Source          string      // source of the chunk
	ShortSrc        string      // short source (for error messages)
	LineDefined     int         // line where definition starts
	LastLineDefined int         // line where definition ends
	CurrentLine     int         // current line
	Name            string      // function name (if known)
	NameWhat        string      // "global", "local", "method", "field", ""
	What            string      // "Lua", "C", "main"
	NUps            int         // number of upvalues
	NParams         int         // number of parameters
	IsVararg        bool        // is a vararg function
	IsTailCall      bool        // is a tail call
	ExtraArgs       int         // number of extra arguments (vararg)
	FTransfer       int         // index of first transferred value (for call/return hooks)
	NTransfer       int         // number of transferred values (for call/return hooks)
	CI              interface{} // internal: *state.CallInfo
	ThreadState     interface{} // internal: *state.LuaState (set by GetStack)
}

DebugInfo holds debug information about a function activation.

type GCWhat

type GCWhat int

GCWhat is the GC operation type.

const (
	GCStop      GCWhat = 0
	GCRestart   GCWhat = 1
	GCCollect   GCWhat = 2
	GCCount     GCWhat = 3
	GCCountB    GCWhat = 4
	GCStep      GCWhat = 5
	GCIsRunning GCWhat = 9
	GCGen       GCWhat = 10
	GCInc       GCWhat = 11
)

type State

type State struct {
	// Internal fields set during construction — not exported.
	// The implementation file will define these.
	Internal any // *state.LuaState (avoids circular import)

	// Writer is the custom output writer for print() and related functions.
	// If nil, os.Stdout is used. Set by pkg/lua.State.SetWriter().
	// Stored here (not on pkg/lua.State) so it survives wrapFunction which
	// creates fresh pkg/lua.State wrappers sharing the same api.State.
	Writer io.Writer

	// FileSystem is the custom filesystem for file loading (require, dofile,
	// loadfile). If nil, the real OS filesystem is used.
	// Stored here (not on pkg/lua.State) so it survives wrapFunction which
	// creates fresh pkg/lua.State wrappers sharing the same api.State.
	FileSystem fs.FS

	// Ctx is the Go context for cancellation/timeout.
	// Stored here (not on pkg/lua.State) so it survives wrapFunction which
	// creates fresh pkg/lua.State wrappers sharing the same api.State.
	// If nil, context.Background() should be assumed by callers.
	Ctx context.Context

	// GlobalSearcher is set by pkg/lua to enable global module registry lookup.
	// It receives a module name and returns a CFunction loader, or nil if not found.
	// This indirection avoids circular imports between pkg/lua and internal/stdlib.
	GlobalSearcher func(name string) CFunction

	// UserData stores arbitrary Go values associated with string keys.
	// Stored here (not on pkg/lua.State) so it survives wrapFunction which
	// creates fresh pkg/lua.State wrappers sharing the same api.State.
	UserData map[string]any
}

State is the public Lua state handle. It wraps the internal LuaState and provides the stack-based API.

func NewState

func NewState() *State

NewState creates a new Lua state.

func (*State) AbsIndex

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

AbsIndex converts a possibly-negative index to absolute.

func (*State) ArgCheck

func (L *State) ArgCheck(cond bool, arg int, extraMsg string)

ArgCheck checks a condition for argument arg. If cond is false, raises an error.

func (*State) ArgError

func (L *State) ArgError(arg int, extraMsg string) int

ArgError raises an error for argument arg. Mirrors: luaL_argerror in lauxlib.c

func (*State) ArgExpected

func (L *State) ArgExpected(cond bool, arg int, tname string)

ArgExpected checks that argument arg has the expected type name.

func (*State) Arith

func (L *State) Arith(op ArithOp)

Arith performs an arithmetic operation.

func (*State) Call

func (L *State) Call(nArgs, nResults int)

Call calls a function. nArgs arguments are on the stack above the function.

func (*State) CallK

func (L *State) CallK(nArgs, nResults int, ctx int, k state.KFunction)

CallK calls a function with a continuation for yielding. If k is non-nil and the coroutine is yieldable, the call is made yieldable and the continuation k will be invoked upon resume after a yield. Otherwise behaves identically to Call (non-yieldable). Mirrors: lua_callk in lapi.c

func (*State) CheckAny

func (L *State) CheckAny(idx int)

CheckAny checks that there is an argument at idx.

func (*State) CheckInteger

func (L *State) CheckInteger(idx int) int64

CheckInteger checks that argument at idx is an integer and returns it. If the value is a float that can't be represented as an int64, raises "has no integer representation" error. If the value is not a number at all, raises "number expected" error. Mirrors: luaL_checkinteger → luaO_str2intX in lauxlib.c / lobject.c.

func (*State) CheckNumber

func (L *State) CheckNumber(idx int) float64

CheckNumber checks that argument at idx is a number and returns it.

func (*State) CheckOption

func (L *State) CheckOption(idx int, def string, opts []string) int

CheckOption checks that the argument at idx is a string matching one of the options. Returns the index of the matched option.

func (*State) CheckStack

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

CheckStack ensures at least n free stack slots.

func (*State) CheckString

func (L *State) CheckString(idx int) string

CheckString checks that argument at idx is a string and returns it.

func (*State) CheckType

func (L *State) CheckType(idx int, tp object.Type)

CheckType checks that argument at idx has the given type.

func (*State) CheckUdata

func (L *State) CheckUdata(idx int, tname string)

CheckUdata checks that the value at idx is a userdata with metatable matching registry[tname]. Raises a type error if not. Mirrors: luaL_checkudata in lauxlib.c

func (*State) ClearHookFields

func (L *State) ClearHookFields()

ClearHookFields clears all hook fields.

func (*State) Close

func (L *State) Close()

Close releases all resources associated with the state.

func (*State) CloseSlot

func (L *State) CloseSlot(idx int)

CloseSlot closes the to-be-closed variable at the given index and sets the slot to nil. The index must be the last marked to-be-closed slot. Uses CLOSEKTOP semantics: does not reset L.Top (preserves stack above). Mirrors: lua_closeslot in lapi.c:206-214

func (*State) Compare

func (L *State) Compare(idx1, idx2 int, op CompareOp) bool

Compare compares two values.

func (*State) Concat

func (L *State) Concat(n int)

Concat concatenates the n values at the top of the stack.

func (*State) Copy

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

Copy copies value at fromIdx to toIdx.

func (*State) CreateTable

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

CreateTable pushes a new table with pre-allocated space.

func (*State) DoFile

func (L *State) DoFile(filename string) error

DoFile loads and executes a file.

func (*State) DoString

func (L *State) DoString(code string) error

DoString loads and executes a string.

func (*State) Dump

func (L *State) Dump(strip bool) []byte

Dump dumps the function at the top of the stack as a binary chunk. If strip is true, debug information is removed. Returns the binary chunk bytes, or nil if the value is not a Lua function. Mirrors: lua_dump in lapi.c

func (*State) Error

func (L *State) Error() int

Error raises a Lua error with the value at the top of the stack.

func (*State) Errorf

func (L *State) Errorf(format string, args ...interface{}) int

Errorf raises a formatted error.

func (*State) GC

func (L *State) GC(what GCWhat, args ...int) int

GC performs a garbage collection operation.

func (*State) GCAgeName

func (L *State) GCAgeName(idx int) string

GCAgeName returns the generational age name for the GC object at idx. Returns "" if the value is not a GC object.

func (*State) GCCollect

func (L *State) GCCollect()

GCCollect runs a full Lua mark-and-sweep GC cycle, then calls all pending __gc finalizers. This is the V5 GC entry point. Mirrors C Lua's luaC_fullgc + callallpendingfinalizers. NOT safe to call during VM execution — use gcMarkSweep for periodic GC.

func (*State) GCColorName

func (L *State) GCColorName(idx int) string

GCColorName returns "white", "gray", or "black" for the GC object at idx. Returns "" if the value is not a GC object.

func (*State) GCObjectAt

func (L *State) GCObjectAt(idx int) *object.GCHeader

GCObjectAt returns the GCHeader for the GC-collectable object at stack index idx. Returns nil if the value is not a GC object (nil, boolean, number, light userdata).

func (*State) GCStateName

func (L *State) GCStateName() string

GCStateName returns the name of the current GC state. Maps GCState byte constants to their C Lua names.

func (*State) GCStepAPI

func (L *State) GCStepAPI() bool

GCStepAPI runs a bounded GC step for collectgarbage("step"). In incremental mode: runs bounded SingleSteps. In generational mode: runs a minor (young) collection. Returns true if a full GC cycle completed during this step. Mirrors C Lua's lua_gc(LUA_GCSTEP).

func (*State) GCTotalBytes

func (L *State) GCTotalBytes() int64

GCTotalBytes returns the Lua-level allocation counter (bytes). Mirrors C Lua's gettotalbytes(g) for collectgarbage("count").

func (*State) GetField

func (L *State) GetField(idx int, key string) object.Type

GetField pushes t[key] where t is at idx.

func (*State) GetFuncProtoInfo

func (L *State) GetFuncProtoInfo(idx int) (source, shortSource, what string, lineDefined, lastLine, nups, nparams int, isVararg, ok bool)

GetFuncProtoInfo inspects a Lua closure at stack index `idx` and returns its Proto metadata. For C functions returns defaults with ok=false.

func (*State) GetGCMode

func (L *State) GetGCMode() string

GetGCMode returns the current GC mode string ("incremental" or "generational"). Defaults to "incremental" if not set.

func (*State) GetGCParam

func (L *State) GetGCParam(name string) int64

GetGCParam returns the current value of a GC parameter. For pause/stepmul/stepsize, reads from the direct GlobalState fields. For other params, falls back to the GCParams map.

func (*State) GetGlobal

func (L *State) GetGlobal(name string) object.Type

GetGlobal pushes the value of global variable name.

func (*State) GetI

func (L *State) GetI(idx int, n int64) object.Type

GetI pushes t[n] where t is at idx. Mirrors lua_geti: handles __index metamethods for non-table types and for table keys that are not found.

func (*State) GetIUserValue

func (L *State) GetIUserValue(idx int, n int) object.Type

GetIUserValue pushes the n-th user value of the userdata at idx onto the stack. Returns the type of the pushed value, or TypeNone if invalid. For non-full-userdata or invalid n, pushes nil and returns TypeNone. Mirrors: lua_getiuservalue in lapi.c

func (*State) GetInfo

func (L *State) GetInfo(what string, ar *DebugInfo) bool

GetInfo fills debug info fields specified by what string. Mirrors: lua_getinfo in lapi.c

func (*State) GetLClosure

func (L *State) GetLClosure(idx int) *closure.LClosure

GetLClosure returns the LClosure at the given stack index, or nil if not a Lua closure.

func (*State) GetLocal

func (L *State) GetLocal(ar *DebugInfo, n int) string

func (*State) GetMetafield

func (L *State) GetMetafield(idx int, field string) bool

GetMetafield pushes the metamethod field from the metatable of the value at idx. Returns true if found (value pushed), false if not (nothing pushed).

func (*State) GetMetatable

func (L *State) GetMetatable(idx int) bool

GetMetatable pushes the metatable of the value at idx.

func (*State) GetStack

func (L *State) GetStack(level int) (*DebugInfo, bool)

GetStack fills a DebugInfo for the given call level.

func (*State) GetSubTable

func (L *State) GetSubTable(idx int, fname string) bool

GetSubTable ensures that t[fname] is a table, creating it if needed. Returns true if the table already existed.

func (*State) GetTable

func (L *State) GetTable(idx int) object.Type

func (*State) GetTop

func (L *State) GetTop() int

GetTop returns the number of elements on the stack (= index of top element).

func (*State) GetUpvalue

func (L *State) GetUpvalue(funcIdx, n int) (string, bool)

GetUpvalue pushes the value of upvalue n of the closure at funcIdx. Returns (name, true) if upvalue exists, ("", false) if not. C closure upvalues are always named "" (empty string).

func (*State) GetUserdataObj

func (L *State) GetUserdataObj(idx int) *object.Userdata

GetUserdataObj returns the full Userdata struct at idx, or nil if not userdata.

func (*State) HasCallFrames

func (L *State) HasCallFrames() bool

HasCallFrames returns true if the thread has call frames above the base CI. Mirrors: lua_getstack(L, 0, &ar) in C Lua — returns true when ci != &L->base_ci.

func (*State) HookActive

func (L *State) HookActive() bool

HookActive returns true if any hooks are set.

func (*State) HookCount

func (L *State) HookCount() int

HookCount returns the base hook count (for count hooks).

func (*State) HookMask

func (L *State) HookMask() int

HookMask returns the current hook mask.

func (*State) Insert

func (L *State) Insert(idx int)

Insert moves top element to idx, shifting up.

func (*State) IsBoolean

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

IsBoolean returns true if the value is a boolean.

func (*State) IsCFunction

func (L *State) IsCFunction(idx int) bool

IsCFunction returns true if the value is a C/Go function.

func (*State) IsFunction

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

IsFunction returns true if the value is a function.

func (*State) IsGCInFinalizer

func (L *State) IsGCInFinalizer() bool

IsGCInFinalizer returns true if a __gc finalizer is currently executing.

func (*State) IsGCRunning

func (L *State) IsGCRunning() bool

IsGCRunning returns true if GC is not stopped.

func (*State) IsInteger

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

IsInteger returns true if the value is an integer.

func (*State) IsNil

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

IsNil returns true if the value at idx is nil.

func (*State) IsNone

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

IsNone returns true if the index is not valid.

func (*State) IsNoneOrNil

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

IsNoneOrNil returns true if the index is not valid or the value is nil.

func (*State) IsNumber

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

IsNumber returns true if the value is a number or convertible string.

func (*State) IsString

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

IsString returns true if the value is a string or a number.

func (*State) IsTable

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

IsTable returns true if the value is a table.

func (*State) IsUserdata

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

IsUserdata returns true if the value is a userdata.

func (*State) IsYieldable

func (L *State) IsYieldable() bool

IsYieldable returns true if the running coroutine can yield.

func (*State) Len

func (L *State) Len(idx int)

Len pushes the length of the value at idx. Mirrors lua_len: calls luaV_objlen which handles __len metamethods.

func (*State) LenI

func (L *State) LenI(idx int) int64

LenI returns the length of the value at idx as an integer (calls __len if needed).

func (*State) Load

func (L *State) Load(code string, name string, mode string) int

Load loads a Lua chunk from a string. Pushes the compiled function.

func (*State) LoadFile

func (L *State) LoadFile(filename string, mode string) int

LoadFile loads a Lua file without executing it. Pushes the compiled chunk as a function on success. Returns a status code (StatusOK on success, or an error code).

func (*State) MemoryLimit

func (L *State) MemoryLimit() int64

MemoryLimit returns the current memory limit (0 = no limit).

func (*State) NewLib

func (L *State) NewLib(funcs map[string]CFunction)

NewLib creates a new table and registers functions into it.

func (*State) NewMetatable

func (L *State) NewMetatable(tname string) bool

NewMetatable creates a new metatable in the registry with the given name. If the registry already has a table with that name, pushes it and returns false. Otherwise creates a new table, stores it in registry[tname], and returns true. Mirrors: luaL_newmetatable in lauxlib.c

func (*State) NewTable

func (L *State) NewTable()

NewTable pushes a new empty table.

func (*State) NewThread

func (L *State) NewThread() *State

NewThread creates a new Lua thread (coroutine), pushes it on the stack, and returns a *State representing the new thread. Mirrors: lua_newthread in lstate.c

func (*State) NewUserdata

func (L *State) NewUserdata(size int, nUV int) *object.Userdata

NewUserdata creates a new full userdata with nUV user values and pushes it. Returns the Userdata object. size is ignored (Go manages memory).

func (*State) Next

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

Next implements table traversal.

func (*State) OptInteger

func (L *State) OptInteger(idx int, def int64) int64

OptInteger returns the integer at idx, or def if nil/none.

func (*State) OptNumber

func (L *State) OptNumber(idx int, def float64) float64

OptNumber returns the number at idx, or def if nil/none.

func (*State) OptString

func (L *State) OptString(idx int, def string) string

OptString returns the string at idx, or def if nil/none.

func (*State) PCall

func (L *State) PCall(nArgs, nResults, msgHandler int) int

PCall performs a protected call. Returns status code.

func (*State) Pop

func (L *State) Pop(n int)

Pop removes n elements from the top.

func (*State) PushBoolean

func (L *State) PushBoolean(b bool)

PushBoolean pushes a boolean.

func (*State) PushCClosure

func (L *State) PushCClosure(f CFunction, n int)

PushCClosure pushes a Go function as a closure with n upvalues.

func (*State) PushCFunction

func (L *State) PushCFunction(f CFunction)

PushCFunction pushes a Go function as a light C function (no upvalues).

func (*State) PushCFunctionSame

func (L *State) PushCFunctionSame(tv object.TValue)

PushCFunctionSame pushes a pre-wrapped C function value. Unlike PushCFunction, which creates a new wrapper each call, this pushes the exact same TValue each time. Use for stateless iterators (e.g., ipairs) where identity must be preserved.

func (*State) PushFString

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

PushFString pushes a formatted string.

func (*State) PushFail

func (L *State) PushFail()

PushFail pushes a "fail" value (false in Lua 5.4+).

func (*State) PushFuncFromDebug

func (L *State) PushFuncFromDebug(ar *DebugInfo) bool

PushFuncFromDebug pushes the function associated with a DebugInfo onto the stack. Returns true if successful, false if the CI is nil or invalid.

func (*State) PushGlobalTable

func (L *State) PushGlobalTable()

PushGlobalTable pushes the global table.

func (*State) PushInteger

func (L *State) PushInteger(n int64)

PushInteger pushes an integer.

func (*State) PushLightUserdata

func (L *State) PushLightUserdata(p interface{})

PushLightUserdata pushes a light userdata.

func (*State) PushNil

func (L *State) PushNil()

PushNil pushes nil.

func (*State) PushNumber

func (L *State) PushNumber(n float64)

PushNumber pushes a float.

func (*State) PushString

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

PushString pushes a string. Returns the string.

func (*State) PushTValue

func (L *State) PushTValue(v object.TValue)

PushTValue pushes an existing TValue directly onto the stack. Unlike PushString etc., this preserves object identity (pointer).

func (*State) PushThread

func (L *State) PushThread() bool

PushThread pushes the running thread onto its own stack. Returns true if the thread is the main thread.

func (*State) PushValue

func (L *State) PushValue(idx int)

PushValue pushes a copy of the value at idx.

func (*State) RawEqual

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

RawEqual compares two values without metamethods.

func (*State) RawGet

func (L *State) RawGet(idx int) object.Type

RawGet pushes t[k] without metamethods.

func (*State) RawGetI

func (L *State) RawGetI(idx int, n int64) object.Type

RawGetI pushes t[n] without metamethods.

func (*State) RawGetP

func (L *State) RawGetP(idx int, p uintptr) object.Type

RawGetP does t[p] where p is a light userdata pointer key. Pushes the result. Mirrors: lua_rawgetp in lapi.c

func (*State) RawLen

func (L *State) RawLen(idx int) int64

RawLen returns the raw length (no __len metamethod).

func (*State) RawSet

func (L *State) RawSet(idx int)

RawSet does t[k] = v without metamethods.

func (*State) RawSetI

func (L *State) RawSetI(idx int, n int64)

RawSetI does t[n] = v without metamethods.

func (*State) RawSetP

func (L *State) RawSetP(idx int, p uintptr)

RawSetP does t[p] = v where p is a light userdata pointer key. v is the value at the top of the stack (popped). Mirrors: lua_rawsetp in lapi.c

func (*State) Ref

func (L *State) Ref(t int) int

Ref creates a reference in the table at idx (luaL_ref). Pops the top value and stores it in the table, returning an integer key. If the value is nil, returns RefNil (-1) and pops the value without storing.

func (*State) Remove

func (L *State) Remove(idx int)

Remove removes element at idx, shifting down.

func (*State) Replace

func (L *State) Replace(idx int)

Replace replaces value at idx with top element, popping top.

func (*State) Require

func (L *State) Require(modname string, openf CFunction, global bool)

Require calls openf to load a module, stores in package.loaded. If the module is already in package.loaded, pushes the cached value. Mirrors luaL_requiref in lauxlib.c.

func (*State) Resume

func (L *State) Resume(from *State, nArgs int) (int, int)

Resume starts or resumes a coroutine. Returns (status, nresults) matching lua_resume in ldo.c. status is StatusOK (finished) or StatusYield (suspended) on success, or an error status on failure.

func (*State) Rotate

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

Rotate rotates the stack elements between idx and top by n positions.

func (*State) RunGCUntilState

func (L *State) RunGCUntilState(targetState byte) string

RunGCUntilState advances the GC state machine by calling SingleStep until it reaches the target state. Returns the state name reached. Used by T.gcstate("statename") in the test library.

func (*State) SetField

func (L *State) SetField(idx int, key string)

SetField does t[key] = v where t is at idx, v at top.

func (*State) SetFuncs

func (L *State) SetFuncs(funcs map[string]CFunction, nUp int)

SetFuncs registers functions from a map into the table at top of stack.

func (*State) SetGCMode

func (L *State) SetGCMode(mode string) string

SetGCMode sets the GC mode and returns the previous mode string. Actually switches the GC between incremental and generational modes.

func (*State) SetGCParam

func (L *State) SetGCParam(name string, value int64) int64

SetGCParam sets a GC parameter and returns the previous value. For pause/stepmul/stepsize, updates the direct GlobalState fields used by the debt-based GC pacer.

func (*State) SetGCStopped

func (L *State) SetGCStopped(stopped bool)

SetGCStopped sets or clears the GCStopped flag (collectgarbage "stop"/"restart").

func (*State) SetGlobal

func (L *State) SetGlobal(name string)

SetGlobal pops a value and sets it as global variable name.

func (*State) SetHookFields

func (L *State) SetHookFields(mask, count int)

SetHookFields sets the hook mask, count, and enable flag on the internal state.

func (*State) SetHookMarker

func (L *State) SetHookMarker()

SetHookMarker sets a non-nil marker in Hook to indicate hooks are active.

func (*State) SetI

func (L *State) SetI(idx int, n int64)

SetI does t[n] = v where t is at idx, v at top.

func (*State) SetIUserValue

func (L *State) SetIUserValue(idx int, n int) bool

SetIUserValue sets the n-th user value of the userdata at idx to the value at the top of the stack. Pops the value. Returns false if the operation fails. Mirrors: lua_setiuservalue in lapi.c

func (*State) SetLocal

func (L *State) SetLocal(ar *DebugInfo, n int) string

func (*State) SetMemoryLimit

func (L *State) SetMemoryLimit(limit int64) int64

SetMemoryLimit sets the maximum memory (in bytes) that Lua objects can use. 0 means no limit. Returns the previous limit. When the limit is exceeded, TrackAllocation attempts a GC cycle and then panics with StatusErrMem if still over limit.

func (*State) SetMetatable

func (L *State) SetMetatable(idx int)

SetMetatable pops a table and sets it as metatable for value at idx.

func (*State) SetStatus

func (L *State) SetStatus(status int)

SetStatus sets the thread status (used by test library for panic simulation).

func (*State) SetTable

func (L *State) SetTable(idx int)

SetTable does t[k] = v where t is at idx, k at top-1, v at top.

func (*State) SetTableMeta

func (L *State) SetTableMeta(idx int)

SetTableMeta does t[k] = v with __newindex metamethod support. Used by testC's settable instruction. Separate from SetTable to avoid Go call stack overflow in deep metamethod chains (events.lua).

func (*State) SetTop

func (L *State) SetTop(idx int)

SetTop sets the stack top to idx. Fills with nil if growing. When shrinking, closes any to-be-closed variables above the new top. Mirrors: lua_settop in lapi.c:179-203

func (*State) SetUpvalue

func (L *State) SetUpvalue(funcIdx, n int) (string, bool)

SetUpvalue sets upvalue n of the closure at funcIdx from the top value. Returns (name, true) if upvalue exists, ("", false) if not.

func (*State) SetWarnF

func (L *State) SetWarnF(f func(ud any, msg string, tocont bool), ud any)

SetWarnF sets the warning handler function. Mirrors C Lua's lua_setwarnf (lapi.c).

func (*State) Status

func (L *State) Status() int

Status returns the status of the coroutine L.

func (*State) StringToNumber

func (L *State) StringToNumber(s string) int

StringToNumber tries to convert a string to a number and pushes it. Returns the length+1 on success, 0 on failure.

func (*State) SweepStrings

func (L *State) SweepStrings()

SweepStrings removes dead interned strings from the string table.

func (*State) TableSizes

func (L *State) TableSizes(idx int) (int, int)

TableSizes returns the array part length and hash part capacity for a table at idx. Returns (0, 0) if the value is not a table.

func (*State) TestUdata

func (L *State) TestUdata(idx int, tname string) bool

TestUdata checks if the value at idx is a userdata with metatable matching registry[tname]. Returns true if it matches, false otherwise. Does not modify the stack. Mirrors: luaL_testudata in lauxlib.c

func (*State) ToBoolean

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

ToBoolean converts the value to boolean.

func (*State) ToClose

func (L *State) ToClose(idx int)

ToClose marks the value at the given index as to-be-closed. Its __close metamethod will be called when the slot goes out of scope. Mirrors: lua_toclose in lapi.c:1288-1296

func (*State) ToGoFunction

func (L *State) ToGoFunction(idx int) CFunction

ToGoFunction returns the Go function at idx, or nil.

func (*State) ToInteger

func (L *State) ToInteger(idx int) (int64, bool)

ToInteger converts the value to integer.

func (*State) ToNumber

func (L *State) ToNumber(idx int) (float64, bool)

ToNumber converts the value to float.

func (*State) ToPointer

func (L *State) ToPointer(idx int) string

func (*State) ToString

func (L *State) ToString(idx int) (string, bool)

ToString converts the value to string.

func (*State) ToThread

func (L *State) ToThread(idx int) *State

ToThread converts the value at the given index to a *State (thread). Returns nil if the value is not a thread.

func (*State) ToUserdata

func (L *State) ToUserdata(idx int) interface{}

func (*State) TolString

func (L *State) TolString(idx int) string

TolString converts the value at idx to a string, using __tostring metamethod if present. Pushes the result on the stack and returns it.

func (*State) TrackAlloc

func (L *State) TrackAlloc(n int64)

TrackAlloc adds n bytes to the Lua-level allocation counter.

func (*State) Type

func (L *State) Type(idx int) object.Type

Type returns the type of the value at idx.

func (*State) TypeError

func (L *State) TypeError(arg int, tname string) int

TypeError raises a type error for argument arg. Mirrors: luaL_typeerror in lauxlib.c — checks __name, then light userdata, then standard name.

func (*State) TypeName

func (L *State) TypeName(tp object.Type) string

TypeName returns the name of the given type.

func (*State) Unref

func (L *State) Unref(t int, ref int)

Unref frees a reference in the table at idx (luaL_unref). Sets t[ref] = nil and adds ref to the free list at t[0].

func (*State) UpvalueId

func (L *State) UpvalueId(funcIdx, n int) interface{}

UpvalueId returns a unique identifier for the upvalue n of the closure at funcIdx. This can be used to check if two closures share the same upvalue. Returns nil if the upvalue doesn't exist. Mirrors: lua_upvalueid in lapi.c

func (*State) UpvalueJoin

func (L *State) UpvalueJoin(funcIdx1, n1, funcIdx2, n2 int)

UpvalueJoin makes the n1-th upvalue of the closure at funcIdx1 refer to the n2-th upvalue of the closure at funcIdx2. Mirrors: lua_upvaluejoin in lapi.c

func (*State) Warning

func (L *State) Warning(msg string, tocont bool)

Warning issues a warning message through the registered handler. tocont=true means the message is a continuation (more parts follow). Mirrors C Lua's lua_warning (lapi.c).

func (*State) Where

func (L *State) Where(level int)

Where pushes "source:line: " for the given call level.

func (*State) XMove

func (L *State) XMove(to *State, n int)

XMove moves n values from L's stack to to's stack. Mirrors: lua_xmove in lapi.c

func (*State) Yield

func (L *State) Yield(nResults int) int

Yield yields a coroutine (no continuation).

func (*State) YieldK

func (L *State) YieldK(nResults int, ctx int, k CFunction) int

YieldK yields a coroutine with a continuation function. Mirrors: lua_yieldk in ldo.c

Jump to

Keyboard shortcuts

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