table

package
v0.3.2 Latest Latest
Warning

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

Go to latest
Published: Apr 27, 2026 License: MIT Imports: 5 Imported by: 0

Documentation

Overview

Package api implements Lua's hybrid array+hash table.

A Lua table has two parts:

  • Array part: integer keys 1..N stored in a Go slice (O(1) access)
  • Hash part: all other keys stored in an open-addressing hash table using Brent's variation for collision resolution

The # (length) operator finds a "boundary" — an index i where t[i] ~= nil and t[i+1] == nil. This is NOT the same as Go's len().

Reference: .analysis/07-runtime-infrastructure.md §3

Hash part internals for Lua tables.

Implements open-addressing hash table with Brent's variation for collision resolution. Reference: lua-master/ltable.c

Table object pool — reuses dead Table structs to reduce allocation pressure.

Tables are the most frequently allocated GC objects in Lua programs (~96% of allocations in GC benchmarks). Using sync.Pool lets us reuse the struct memory for short-lived tables instead of going through Go's mallocgc each time.

Core Table operations for Lua tables.

Implements Get, Set, RawLen, Next, and constructor. Reference: lua-master/ltable.c

Index

Constants

View Source
const (
	WeakKey   byte = 1 // bit 0: weak keys
	WeakValue byte = 2 // bit 1: weak values
)

Weak table mode constants.

Variables

View Source
var ErrInvalidKey = errors.New("invalid key to 'next'")

ErrInvalidKey is returned by Next when the given key is not in the table.

Functions

func PutTable

func PutTable(t *Table)

PutTable returns a Table to the pool for reuse. Called by the GC sweep phase when a dead table is unlinked. Clears all reference fields before pooling to help Go's GC.

Types

type Table

type Table struct {
	object.GCHeader                 // GC metadata
	Array           []object.TValue // array part: indices 0..len-1 map to Lua keys 1..len
	Nodes           []node          // hash part: open-addressing with Brent's variation
	LsizeNode       uint8           // log2(len(nodes)), 0 if nodes == nil
	LastFree        int             // index for free-slot backward scan
	Flags           byte            // metamethod absence cache (bit p = TM p absent)
	Metatable       *Table          // metatable or nil

	// Weak table support (__mode metafield)
	WeakMode byte // bit 0 = weak keys, bit 1 = weak values

	// SizeDelta accumulates the net change in ObjSize from table resizes.
	// The VM/API layer checks this after table mutations and calls
	// TrackAllocation to update GCDebt. Reset to 0 after consumption.
	SizeDelta int64
}

Table is a Lua table with hybrid array + hash storage.

func New

func New(arraySize, hashSize int) *Table

New creates an empty Lua table. arraySize and hashSize are hints for pre-allocation. hashSize will be rounded up to the next power of 2.

func (*Table) ArrayLen

func (t *Table) ArrayLen() int

ArrayLen returns the allocated array part length.

func (*Table) EstimateBytes

func (t *Table) EstimateBytes() int64

EstimateBytes returns an approximate byte size for this table, mirroring C Lua's allocation tracking for collectgarbage("count"). sizeof(Table)=80, sizeof(TValue)=24, sizeof(Node)=56 on 64-bit Go.

func (*Table) GC

func (t *Table) GC() *object.GCHeader

GC returns the GC header for this table.

func (*Table) Get

func (t *Table) Get(key object.TValue) (object.TValue, bool)

Get retrieves the value for the given key. Returns (value, found). If the key is not present, returns (object.Nil, false). For integer keys in the array range, accesses the array part directly.

func (*Table) GetInt

func (t *Table) GetInt(key int64) (object.TValue, bool)

GetInt retrieves the value for an integer key. Checks the array part first, then the hash part.

func (*Table) GetMetatable

func (t *Table) GetMetatable() *Table

GetMetatable returns the table's metatable (may be nil).

func (*Table) GetStr

func (t *Table) GetStr(key *object.LuaString) (object.TValue, bool)

GetStr retrieves the value for a short string key. Uses pointer equality for interned short strings (O(1) amortized).

func (*Table) HasTagMethod

func (t *Table) HasTagMethod(tm byte) bool

HasTagMethod returns true if the metamethod at index tm might be present. false = definitely absent (cached). true = might be present (check metatable). tm is a TMS enum value (0 = TM_INDEX, ..., 5 = TM_EQ are fast-cached).

func (*Table) HasWeakKeys

func (t *Table) HasWeakKeys() bool

HasWeakKeys returns true if this table has weak keys (__mode contains "k").

func (*Table) HasWeakValues

func (t *Table) HasWeakValues() bool

HasWeakValues returns true if this table has weak values (__mode contains "v").

func (*Table) HashLen

func (t *Table) HashLen() int

HashLen returns the hash part capacity (always a power of 2, or 0).

func (*Table) InvalidateFlags

func (t *Table) InvalidateFlags()

InvalidateFlags clears the metamethod absence cache. Must be called when the metatable changes.

func (*Table) Next

func (t *Table) Next(key object.TValue) (nextKey, nextVal object.TValue, ok bool, err error)

Next advances the iterator past the given key and returns the next (key, value) pair. To start iteration, pass object.Nil as key. Returns (key, value, true) for the next entry, or (Nil, Nil, false) when done. Iteration order: array part first (keys 1..N), then hash part.

func (*Table) RawLen

func (t *Table) RawLen() int64

RawLen returns the "raw" length of the table (the # operator result). This finds a boundary: an index i where t[i] ~= nil and t[i+1] == nil.

func (*Table) ResizeArray

func (t *Table) ResizeArray(newSize int)

ResizeArray grows or shrinks the array part to exactly newSize. Matches C Lua's luaH_resizearray: keeps the hash part unchanged, migrates elements between array and hash as needed. Used by OP_SETLIST to pre-allocate the exact array size.

func (*Table) Set

func (t *Table) Set(key, value object.TValue)

Set sets the value for the given key. Panics if key is nil or NaN. If the key is new and the hash part is full, triggers a rehash.

func (*Table) SetIfExists

func (t *Table) SetIfExists(key, value object.TValue) bool

SetIfExists overwrites the value for an existing key and returns true. If the key is not found, returns false without modifying the table. This is the "fast set" path — no insertion, no rehash, single hash lookup.

func (*Table) SetInt

func (t *Table) SetInt(key int64, value object.TValue)

SetInt sets the value for an integer key.

func (*Table) SetMetatable

func (t *Table) SetMetatable(mt *Table)

SetMetatable sets the table's metatable.

func (*Table) SetNoTagMethod

func (t *Table) SetNoTagMethod(tm byte)

SetNoTagMethod marks the given tag method as absent in the cache.

func (*Table) SetStr

func (t *Table) SetStr(key *object.LuaString, value object.TValue)

SetStr sets the value for a short string key.

Jump to

Keyboard shortcuts

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