forked from zxh0/luago-book
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlua_table.go
101 lines (91 loc) · 1.82 KB
/
lua_table.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
package state
import "math"
import "luago/number"
type luaTable struct {
arr []luaValue
_map map[luaValue]luaValue
}
func newLuaTable(nArr, nRec int) *luaTable {
t := &luaTable{}
if nArr > 0 {
t.arr = make([]luaValue, 0, nArr)
}
if nRec > 0 {
t._map = make(map[luaValue]luaValue, nRec)
}
return t
}
func (self *luaTable) len() int {
return len(self.arr)
}
func (self *luaTable) get(key luaValue) luaValue {
key = _floatToInteger(key)
if idx, ok := key.(int64); ok {
if idx >= 1 && idx <= int64(len(self.arr)) {
return self.arr[idx-1]
}
}
return self._map[key]
}
func _floatToInteger(key luaValue) luaValue {
if f, ok := key.(float64); ok {
if i, ok := number.FloatToInteger(f); ok {
return i
}
}
return key
}
func (self *luaTable) put(key, val luaValue) {
if key == nil {
panic("table index is nil!")
}
if f, ok := key.(float64); ok && math.IsNaN(f) {
panic("table index is NaN!")
}
key = _floatToInteger(key)
if idx, ok := key.(int64); ok && idx >= 1 {
arrLen := int64(len(self.arr))
if idx <= arrLen {
self.arr[idx-1] = val
if idx == arrLen && val == nil {
self._shrinkArray()
}
return
}
if idx == arrLen+1 {
delete(self._map, key)
if val != nil {
self.arr = append(self.arr, val)
self._expandArray()
}
return
}
}
if val != nil {
if self._map == nil {
self._map = make(map[luaValue]luaValue, 8)
}
self._map[key] = val
} else {
delete(self._map, key)
}
}
func (self *luaTable) _shrinkArray() {
for i := len(self.arr) - 1; i >= 0; i-- {
if self.arr[i] == nil {
self.arr = self.arr[0:i]
} else {
break
}
}
}
func (self *luaTable) _expandArray() {
for idx := int64(len(self.arr)) + 1; true; idx++ {
if val, found := self._map[idx]; found {
delete(self._map, idx)
self.arr = append(self.arr, val)
} else {
break
}
}
}