Documentation
¶
Overview ¶
Package api defines Lua's universal value type (TValue) and all Lua types.
Every Lua value is represented as a TValue: a type tag (Tag) plus a Go value (any). This is the Go equivalent of C Lua's tagged union (lobject.h).
Design priority: Correctness > Simplicity > Performance. Reference: .analysis/03-object-type-system.md
Arithmetic operations for Lua values (used by constant folding and VM).
Reference: lua-master/lobject.c (luaO_rawarith, intarith, numarith)
String↔number coercion and number formatting for Lua values.
Reference: lua-master/lobject.c (luaO_str2num, tostringbuffFloat, l_str2int, l_str2d)
Additional TValue constructors, accessors, and comparison helpers.
These extend the base types defined in api.go with constructors for GC object types and raw equality comparison.
Index ¶
- Constants
- Variables
- func AnyDataPtr(val any) unsafe.Pointer
- func CeilLog2(x uint) byte
- func FloatIDiv(a, b float64) float64
- func FloatMod(a, b float64) float64
- func FloatToInteger(f float64) (int64, bool)
- func FloatToString(f float64) string
- func FuncDataPtr(val any) uintptr
- func IntIDiv(a, b int64) int64
- func IntMod(a, b int64) int64
- func IntegerToString(i int64) string
- func IsLuaAlNum(r rune) bool
- func IsLuaAlpha(r rune) bool
- func IsLuaDigit(r rune) bool
- func IsLuaSpace(r rune) bool
- func LightCFuncEqual(a, b any) bool
- func RawEqual(v1, v2 TValue) bool
- func SetObj(dst *TValue, src TValue)
- func ShiftLeft(x, y int64) int64
- func StringToFloat(s string) (float64, bool)
- func StringToInteger(s string) (int64, bool)
- func ToIntegerNS(v TValue) (int64, bool)
- func TypeNameOf(v TValue) string
- type AbsLineInfo
- type GCHeader
- type GCObject
- type LocVar
- type LuaString
- type Proto
- type StackValue
- type TValue
- func MakeBoolean(b bool) TValue
- func MakeCClosure(c any) TValue
- func MakeFloat(f float64) TValue
- func MakeFromPayload(tt Tag, payload any) TValue
- func MakeInteger(i int64) TValue
- func MakeLightCFunc(f any) TValue
- func MakeLightUserdata(p any) TValue
- func MakeLuaClosure(c any) TValue
- func MakeProto(p *Proto) TValue
- func MakeString(s *LuaString) TValue
- func MakeTable(t any) TValue
- func MakeThread(t any) TValue
- func MakeUserdata(u *Userdata) TValue
- func RawArith(op int, p1, p2 TValue) (TValue, bool)
- func StringToNumber(s string) (TValue, bool)
- func (v TValue) Boolean() bool
- func (v TValue) CClosureVal() any
- func (v TValue) ClosureVal() any
- func (v TValue) Float() float64
- func (v TValue) GCValue() any
- func (v TValue) Integer() int64
- func (v TValue) IsFalsy() bool
- func (v TValue) IsFloat() bool
- func (v TValue) IsFunction() bool
- func (v TValue) IsInteger() bool
- func (v TValue) IsNil() bool
- func (v TValue) IsNumber() bool
- func (v TValue) IsString() bool
- func (v TValue) IsTable() bool
- func (v TValue) LightCFuncVal() any
- func (v TValue) LightUserdataVal() any
- func (v TValue) LuaClosureVal() any
- func (v TValue) Payload() any
- func (v TValue) ProtoVal() *Proto
- func (v TValue) StringVal() *LuaString
- func (v TValue) TableVal() any
- func (v TValue) Tag() Tag
- func (v TValue) ThreadVal() any
- func (v TValue) ToInteger() (int64, bool)
- func (v TValue) ToNumber() (float64, bool)
- func (v TValue) Type() Type
- func (v TValue) UserdataVal() *Userdata
- type Tag
- type Type
- type UpvalDesc
- type Userdata
Constants ¶
const ( WhiteBit0 byte = 1 << 0 // white bit 0 WhiteBit1 byte = 1 << 1 // white bit 1 BlackBit byte = 1 << 2 // black bit FinalizedBit byte = 1 << 3 // has been finalized )
GC color/mark bit constants.
const ( G_NEW byte = 0 // created in current cycle G_SURVIVAL byte = 1 // survived one cycle G_OLD0 byte = 2 // marked old by forward barrier in this cycle G_OLD1 byte = 3 // first full cycle as old G_OLD byte = 4 // really old object (not visited in minor GC) G_TOUCHED1 byte = 5 // old object touched this cycle G_TOUCHED2 byte = 6 // old object touched in previous cycle )
Generational GC age constants (stored in GCHeader.Age, not in Marked). Mirrors C Lua's G_NEW through G_TOUCHED2 (lgc.h:110-116).
const ( GCSpause byte = 0 // waiting to start a new cycle GCSpropagate byte = 1 // propagating gray objects GCSenteratomic byte = 2 // about to enter atomic phase GCSatomic byte = 3 // atomic mark phase GCSswpallgc byte = 4 // sweeping allgc list GCSswpfinobj byte = 5 // sweeping finobj list GCSswptobefnz byte = 6 // sweeping tobefnz list GCSswpend byte = 7 // sweep finished GCScallfin byte = 8 // calling finalizers )
GC phase constants (matches C Lua's GCState values from lgc.h).
const ( KGC_INC byte = 0 // incremental mode (default) KGC_GENMINOR byte = 1 // generational mode — minor collection KGC_GENMAJOR byte = 2 // generational mode — major collection )
GC kind constants (matches C Lua's KGC_* from lgc.h).
const ( PF_VAHID byte = 1 // function has hidden vararg arguments PF_VATAB byte = 2 // function has vararg table (Lua 5.5) PF_FIXED byte = 4 // prototype has parts in fixed memory )
--------------------------------------------------------------------------- Proto flag constants (C7 FIX: replaces IsVararg bool) ---------------------------------------------------------------------------
const ( LuaOpAdd = 0 // LUA_OPADD LuaOpSub = 1 // LUA_OPSUB LuaOpMul = 2 // LUA_OPMUL LuaOpMod = 3 // LUA_OPMOD LuaOpPow = 4 // LUA_OPPOW LuaOpDiv = 5 // LUA_OPDIV LuaOpIDiv = 6 // LUA_OPIDIV LuaOpBAnd = 7 // LUA_OPBAND LuaOpBOr = 8 // LUA_OPBOR LuaOpBXor = 9 // LUA_OPBXOR LuaOpShl = 10 // LUA_OPSHL LuaOpShr = 11 // LUA_OPSHR LuaOpUnm = 12 // LUA_OPUNM LuaOpBNot = 13 // LUA_OPBNOT )
Lua arithmetic operation codes (matches C lua.h LUA_OP*)
const LuaNumberFmt = "%.15g"
LuaNumberFmt is the default format for writing floats (%.15g for double).
const LuaNumberFmtN = "%.17g"
LuaNumberFmtN is the higher-precision format used when %.15g loses precision.
const NumTypes = 9
NumTypes is the count of public Lua types (LUA_NUMTYPES = 9).
const WhiteBits = WhiteBit0 | WhiteBit1
WhiteBits is the mask for both white bits.
Variables ¶
var AbsentKey = TValue{Tt: TagAbstKey}
AbsentKey is the singleton absent-key TValue.
var Empty = TValue{Tt: TagEmpty}
Empty is the singleton empty-slot TValue.
var False = TValue{Tt: TagFalse}
False is the singleton false TValue.
var Nil = TValue{Tt: TagNil}
Nil is the singleton nil TValue.
var ReconstructObj func(tt Tag, ptr unsafe.Pointer) any
ReconstructObj is a callback that reconstructs an `any` from a type tag and an unsafe.Pointer for rare collectable key types (table-as-key, userdata-as-key, closure-as-key, thread-as-key). It is registered at init time by the api package which has access to all concrete types.
This avoids import cycles: the table package can't import state/closure, but needs to return properly-typed TValues from nodeKey() for next() iteration.
var True = TValue{Tt: TagTrue}
True is the singleton true TValue.
var TypeNames = [NumTypes]string{
"nil", "boolean", "userdata", "number",
"string", "table", "function", "userdata", "thread",
}
TypeNames maps base types to their display names.
Functions ¶
func AnyDataPtr ¶ added in v0.5.0
AnyDataPtr extracts the data pointer from an any interface value. Used by table node setNodeKey and equalKey for pointer identity comparison.
func FloatToInteger ¶
FloatToInteger checks if float f has an integer representation (fits in int64 without loss of precision). Returns (int, true) if so, or (0, false) if f is not an integer or overflows int64. Mirrors: luaO_cast_number2int in lobject.c.
func FloatToString ¶
FloatToString converts a Lua float to its string representation.
Algorithm (from C lobject.c tostringbuffFloat):
- Format with %.15g
- Parse back; if the value differs, re-format with %.17g
- If the result looks like an integer (no '.', no 'e/E'), append ".0"
Special cases: +Inf → "inf", -Inf → "-inf", NaN → "-nan" or "nan".
func FuncDataPtr ¶
FuncDataPtr returns the interface data-word for a func value stored in an any. This is unique per closure instance even when multiple closures share the same function literal. Returns 0 for nil.
func IntegerToString ¶
IntegerToString converts a Lua integer to its string representation. Equivalent to C's lua_integer2str: plain decimal format.
func IsLuaAlNum ¶
IsLuaAlNum reports whether the rune is alphanumeric or underscore.
func IsLuaAlpha ¶
IsLuaAlpha reports whether the rune is a Lua "alpha" character (letter or _).
func IsLuaDigit ¶
IsLuaDigit reports whether the rune is an ASCII digit.
func IsLuaSpace ¶
IsLuaSpace reports whether the rune is a Lua whitespace character.
func LightCFuncEqual ¶
LightCFuncEqual returns true if two light C function values (stored as any) refer to the same closure instance.
func RawEqual ¶
RawEqual compares two TValues for raw equality (no metamethods).
Rules:
- Different base types → false
- Same base type, different variant:
- integer vs float → compare values (float must be exact integer)
- short string vs long string → compare content
- all others → false
- Same variant:
- nil, false, true → true (singletons)
- integer → value equality
- float → value equality (NaN != NaN)
- short string → pointer equality (interned)
- long string → content equality
- everything else → pointer identity
func StringToFloat ¶
StringToFloat attempts to parse a string as a Lua float. Supports decimal, hexadecimal floats (0x with optional p exponent). Rejects "inf" and "nan" (Lua does not accept these as valid number literals).
Reference: lua-master/lobject.c l_str2d
func StringToInteger ¶
StringToInteger attempts to parse a string as a Lua integer. Supports decimal and hexadecimal (0x/0X prefix). Skips leading/trailing whitespace. Rejects overflow for decimal.
Reference: lua-master/lobject.c l_str2int
func ToIntegerNS ¶
ToIntegerNS converts to integer with floor mode (for bitwise ops). Mirrors: luaV_tointegerns with LUA_FLOORN2I mode.
Types ¶
type AbsLineInfo ¶
AbsLineInfo maps a PC to an absolute source line number.
type GCHeader ¶
type GCHeader struct {
Next GCObject // next in allgc/finobj/tobefnz chain
Marked byte // GC mark bits: color (white0/white1/black) + finalized
Age byte // generational GC age (G_NEW through G_TOUCHED2)
// ObjSize is the pre-computed byte size of this object for GC accounting.
// Set at allocation time. Updated on table resize (rehash).
// Used by sweepList to decrement GCTotalBytes without type assertions.
ObjSize int64
}
GCHeader is embedded in every collectable Lua object. It provides the linked-list pointer for the Lua GC allgc chain.
Gray/weak/ephemeron lists use external slices in GlobalState instead of an intrusive GCList pointer, saving 16 bytes per object (interface = 16B).
func FastGC ¶ added in v0.3.2
FastGC extracts *GCHeader from a GCObject interface without calling the GC() method (avoiding interface dispatch overhead).
SAFETY INVARIANT: Every type implementing GCObject MUST embed GCHeader as its FIRST field. This ensures the interface's data pointer points directly to the GCHeader.
This is 3.9x faster than obj.GC() when multiple concrete types exist, because it avoids the indirect call through the interface method table.
func FastGCFromAny ¶ added in v0.3.2
FastGCFromAny extracts *GCHeader from an `any` value without type assertion. The any value MUST contain a pointer to a struct with GCHeader as first field. Used in markValue to check IsWhite() before the expensive GCObject type assertion.
func NodeKeyGCHeader ¶ added in v0.5.0
NodeKeyGCHeader returns the GCHeader pointer for a node key stored as an unsafe.Pointer. The key must be a collectable type (BIT_ISCOLLECTABLE set). This is the equivalent of FastGCFromAny but for the split-field layout.
func (*GCHeader) IsDead ¶
IsDead returns true if the object is dead. Matches C Lua's isdeadm: (m) & (ow).
func (*GCHeader) IsOld ¶
IsOld returns true if the object is older than SURVIVAL (OLD0, OLD1, OLD, TOUCHED1, TOUCHED2).
type GCObject ¶
type GCObject interface {
GC() *GCHeader
}
GCObject is the interface all GC-collectable Lua objects implement.
type LocVar ¶
type LocVar struct {
Name *LuaString
StartPC int // first active instruction
EndPC int // first dead instruction
}
LocVar describes a local variable's lifetime.
type LuaString ¶
type LuaString struct {
GCHeader // GC metadata
Data string
Hash_ uint32
IsShort bool
Extra byte // reserved word flag for short strings
}
LuaString wraps a Go string with interning support and hash caching.
type Proto ¶
type Proto struct {
GCHeader // GC metadata
Code []uint32 // bytecode instructions
Constants []TValue // constant pool
Protos []*Proto // nested function prototypes
Upvalues []UpvalDesc // upvalue descriptors
NumParams byte // number of fixed parameters
MaxStackSize byte // registers needed
Flag byte // function flags (PF_VAHID, PF_VATAB, PF_FIXED)
LineDefined int // first line of definition
LastLine int // last line of definition
Source *LuaString // source file name
// Debug info (optional, can be stripped)
LineInfo []int8 // per-instruction line delta
AbsLineInfo []AbsLineInfo // sparse absolute line info
LocVars []LocVar // local variable info
}
Proto represents a compiled Lua function (the bytecode + metadata). This is the Go equivalent of C Lua's Proto struct (lobject.h:492–515).
type StackValue ¶
type StackValue struct {
Val TValue
TBCDelta uint16 // distance to previous tbc variable (0 = not tbc)
}
StackValue is a stack slot: a TValue plus a delta for the to-be-closed list.
type TValue ¶
type TValue struct {
Tt Tag // type tag
N int64 // numeric payload: int64 for integers, float64 bits for floats
Obj any // GC object payload: *LuaString | *Table | *LClosure | etc.
}
TValue represents any Lua value using a dual-field layout for zero-alloc numerics.
Numeric types (integer, float) are stored in the N field without boxing:
- Integer: N holds the int64 value directly
- Float: N holds the float64 bits via math.Float64bits/Float64frombits
GC object types (string, table, closure, userdata, thread, proto, upval) are stored in the Obj field as typed pointers.
This eliminates runtime.convT64 allocations on the hot path.
func MakeBoolean ¶
MakeBoolean creates a boolean TValue (TagFalse or TagTrue).
func MakeCClosure ¶
MakeCClosure creates a C closure TValue. c should be a *closure.CClosure.
func MakeFromPayload ¶
MakeFromPayload reconstructs a TValue from a tag and a payload (as returned by Payload()). Used in table node key reconstruction.
func MakeInteger ¶
MakeInteger creates an integer TValue. Stored inline in N — zero allocation.
func MakeLightCFunc ¶
MakeLightCFunc creates a light C function TValue (no upvalues). f should be a state.CFunction.
func MakeLightUserdata ¶
MakeLightUserdata creates a light userdata TValue. p is an arbitrary Go value used as an opaque pointer.
func MakeLuaClosure ¶
MakeLuaClosure creates a Lua closure TValue. c should be a *closure.LClosure.
func MakeString ¶
MakeString creates a string TValue from a *LuaString. The tag is taken from the LuaString itself (short or long).
func MakeThread ¶
MakeThread creates a thread TValue. t should be a *state.LuaState.
func MakeUserdata ¶
MakeUserdata creates a full userdata TValue.
func RawArith ¶
RawArith performs raw arithmetic on TValues (no metamethods). Returns (result, true) on success, (Nil, false) on failure. Mirrors: luaO_rawarith in lobject.c
func StringToNumber ¶
StringToNumber attempts to convert a string to a Lua number. It tries integer first, then float (matching C's luaO_str2num). Returns the TValue and true on success, or (Nil, false) on failure.
func (TValue) CClosureVal ¶
CClosureVal returns the C closure pointer. Panics if not a C closure.
func (TValue) ClosureVal ¶
ClosureVal returns the closure pointer (Lua or C). Panics if not a function.
func (TValue) IsFunction ¶
IsFunction returns true if this is any function variant.
func (TValue) LightCFuncVal ¶
LightCFuncVal returns the light C function. Panics if not a light C function.
func (TValue) LightUserdataVal ¶
LightUserdataVal returns the light userdata value. Panics if not light userdata.
func (TValue) LuaClosureVal ¶
LuaClosureVal returns the Lua closure pointer. Panics if not a Lua closure.
func (TValue) Payload ¶
Payload returns a boxed representation of the value for use in rare paths (e.g., table hash keys). For integers it boxes N, for floats it boxes the float64, for everything else it returns Obj. This DOES allocate for numbers but is only used in cold paths (table key storage).
func (TValue) ToInteger ¶
ToInteger attempts to convert to int64. Returns (value, ok). Integer → identity. Float → truncate if exact. Other → false.
func (TValue) ToNumber ¶
ToNumber attempts to convert to float64. Returns (value, ok). Integer → float64 conversion. Float → identity. Other → false.
func (TValue) UserdataVal ¶
UserdataVal returns the Userdata pointer. Panics if not a full userdata.
type Tag ¶
type Tag byte
Tag is the full type tag with variant bits (bits 0–5 of the tag byte). Bit layout: [7:unused][6:collectable][5:variant1][4:variant0][3:0:base_type]
const ( TagNil Tag = 0x00 // LUA_VNIL — standard nil TagEmpty Tag = 0x10 // LUA_VEMPTY — empty table slot TagAbstKey Tag = 0x20 // LUA_VABSTKEY — absent key (key not found) TagNotable Tag = 0x30 // LUA_VNOTABLE — fast-get hit a non-table (Lua 5.5 new) )
Nil variants (4 kinds in Lua 5.5) — NOT collectable
Boolean variants — NOT collectable
Number variants — NOT collectable
const ( TagShortStr Tag = 0x44 // LUA_VSHRSTR — interned short string TagLongStr Tag = 0x54 // LUA_VLNGSTR — non-interned long string )
String variants — collectable (bit 6 set)
const ( TagLuaClosure Tag = 0x46 // LUA_VLCL — Lua closure (collectable) TagLightCFunc Tag = 0x16 // LUA_VLCF — light C function (NOT collectable) TagCClosure Tag = 0x66 // LUA_VCCL — C closure (collectable) )
Function variants
const ( TagTable Tag = 0x45 // LUA_VTABLE TagUserdata Tag = 0x47 // LUA_VUSERDATA TagThread Tag = 0x48 // LUA_VTHREAD TagUpVal Tag = 0x49 // LUA_VUPVAL (internal) TagProto Tag = 0x4A // LUA_VPROTO (internal) TagLightUserdata Tag = 0x02 // LUA_VLIGHTUSERDATA (NOT collectable) )
Other collectable types (bit 6 set)
const BIT_ISCOLLECTABLE Tag = 0x40
BIT_ISCOLLECTABLE marks a tag as a GC-collectable type. Matches C Lua's BIT_ISCOLLECTABLE (bit 6).
const TagDeadKey Tag = 0x0B // LUA_TDEADKEY (NOT collectable)
TagDeadKey is used for dead keys in table hash part (internal).
func (Tag) IsCollectable ¶ added in v0.3.1
IsCollectable returns true if this tag represents a GC-collectable type.
func (Tag) IsStrictNil ¶
IsStrictNil returns true only for standard nil (not empty/abstkey/notable).
type Type ¶
type Type byte
Type is the base Lua type (bits 0–3 of the tag byte).
const ( TypeNil Type = 0 // LUA_TNIL TypeBoolean Type = 1 // LUA_TBOOLEAN TypeLightUserdata Type = 2 // LUA_TLIGHTUSERDATA TypeNumber Type = 3 // LUA_TNUMBER TypeString Type = 4 // LUA_TSTRING TypeTable Type = 5 // LUA_TTABLE TypeFunction Type = 6 // LUA_TFUNCTION TypeUserdata Type = 7 // LUA_TUSERDATA TypeThread Type = 8 // LUA_TTHREAD TypeNone Type = 0xFF // LUA_TNONE — invalid/absent (API only) )
type UpvalDesc ¶
type UpvalDesc struct {
Name *LuaString // upvalue name (debug)
InStack bool // true = in enclosing function's stack (register)
Idx byte // index in stack or in outer function's upvalue list
Kind byte // kind of corresponding variable
}
UpvalDesc describes how an upvalue is captured.
type Userdata ¶
type Userdata struct {
GCHeader // GC metadata
Data any // user data (Go value)
MetaTable any // *Table at runtime (any to avoid import cycle)
UserVals []TValue // user values (nuvalue)
Size int // allocated size in bytes (for lua_rawlen)
}
Userdata represents a full userdata object. It holds arbitrary Go data, a metatable, and user values.