github.com/arnodel/golua@v0.0.0-20230215163904-e0b5347eaaa1/runtime/table.go (about)

     1  package runtime
     2  
     3  import (
     4  	"unsafe"
     5  
     6  	"github.com/arnodel/golua/runtime/internal/luagc"
     7  )
     8  
     9  // Table implements a Lua table.
    10  type Table struct {
    11  	// This is where the implementation details are.
    12  	*mixedTable
    13  
    14  	meta *Table
    15  }
    16  
    17  // NewTable returns a new Table.
    18  func NewTable() *Table {
    19  	return &Table{mixedTable: &mixedTable{}}
    20  }
    21  
    22  // Metatable returns the table's metatable.
    23  func (t *Table) Metatable() *Table {
    24  	return t.meta
    25  }
    26  
    27  // SetMetatable sets the table's metatable.
    28  func (t *Table) SetMetatable(m *Table) {
    29  	t.meta = m
    30  }
    31  
    32  var _ luagc.Value = (*Table)(nil)
    33  
    34  func (t *Table) Key() luagc.Key {
    35  	return unsafe.Pointer(t.mixedTable)
    36  }
    37  
    38  func (t *Table) Clone() luagc.Value {
    39  	clone := new(Table)
    40  	*clone = *t
    41  	return clone
    42  }
    43  
    44  // Get returns t[k].
    45  func (t *Table) Get(k Value) Value {
    46  	return t.get(k)
    47  }
    48  
    49  // Set implements t[k] = v (doesn't check if k is nil).
    50  func (t *Table) Set(k, v Value) uint64 {
    51  	if v.IsNil() {
    52  		t.mixedTable.remove(k)
    53  		return 0
    54  	}
    55  	t.mixedTable.insert(k, v)
    56  	return 16
    57  }
    58  
    59  // Reset implements t[k] = v only if t[k] was already non-nil.
    60  func (t *Table) Reset(k, v Value) (wasSet bool) {
    61  	if v.IsNil() {
    62  		return t.mixedTable.remove(k)
    63  	}
    64  	return t.mixedTable.reset(k, v)
    65  }
    66  
    67  // Len returns a length for t (see lua docs for details).
    68  func (t *Table) Len() int64 {
    69  	return int64(t.mixedTable.len())
    70  }
    71  
    72  // Next returns the key-value pair that comes after k in the table t.
    73  func (t *Table) Next(k Value) (next Value, val Value, ok bool) {
    74  	return t.mixedTable.next(k)
    75  }