forked from zxh0/luago-book
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlua_stack.go
More file actions
106 lines (93 loc) · 1.82 KB
/
Copy pathlua_stack.go
File metadata and controls
106 lines (93 loc) · 1.82 KB
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
102
103
104
105
106
package state
type luaStack struct {
/* virtual stack */
slots []luaValue
top int
/* call info */
closure *closure
varargs []luaValue
pc int
/* linked list */
prev *luaStack
}
func newLuaStack(size int) *luaStack {
return &luaStack{
slots: make([]luaValue, size),
top: 0,
}
}
func (self *luaStack) check(n int) {
free := len(self.slots) - self.top
for i := free; i < n; i++ {
self.slots = append(self.slots, nil)
}
}
func (self *luaStack) push(val luaValue) {
if self.top == len(self.slots) {
panic("stack overflow!")
}
self.slots[self.top] = val
self.top++
}
func (self *luaStack) pop() luaValue {
if self.top < 1 {
panic("stack underflow!")
}
self.top--
val := self.slots[self.top]
self.slots[self.top] = nil
return val
}
func (self *luaStack) pushN(vals []luaValue, n int) {
nVals := len(vals)
if n < 0 {
n = nVals
}
for i := 0; i < n; i++ {
if i < nVals {
self.push(vals[i])
} else {
self.push(nil)
}
}
}
func (self *luaStack) popN(n int) []luaValue {
vals := make([]luaValue, n)
for i := n - 1; i >= 0; i-- {
vals[i] = self.pop()
}
return vals
}
func (self *luaStack) absIndex(idx int) int {
if idx >= 0 {
return idx
}
return idx + self.top + 1
}
func (self *luaStack) isValid(idx int) bool {
absIdx := self.absIndex(idx)
return absIdx > 0 && absIdx <= self.top
}
func (self *luaStack) get(idx int) luaValue {
absIdx := self.absIndex(idx)
if absIdx > 0 && absIdx <= self.top {
return self.slots[absIdx-1]
}
return nil
}
func (self *luaStack) set(idx int, val luaValue) {
absIdx := self.absIndex(idx)
if absIdx > 0 && absIdx <= self.top {
self.slots[absIdx-1] = val
return
}
panic("invalid index!")
}
func (self *luaStack) reverse(from, to int) {
slots := self.slots
for from < to {
slots[from], slots[to] = slots[to], slots[from]
from++
to--
}
}