This repository has been archived by the owner on Aug 2, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 84
/
closure.go
105 lines (87 loc) · 1.92 KB
/
closure.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
102
103
104
105
package lua
import (
"fmt"
"github.com/Azure/golua/lua/binary"
)
type (
// closure represents a lua or go function closure.
Closure struct {
binary *binary.Prototype
native Func
upvals []*upValue
}
// upValue holds external local variable state.
upValue struct {
frame *Frame // frame upValue was opened within.
index int // index into stack or enclosing function.
value Value // if closed.
}
)
func newLuaClosure(proto *binary.Prototype) *Closure {
cls := &Closure{binary: proto}
if nups := len(proto.UpValues); nups > 0 {
cls.upvals = make([]*upValue, nups)
}
return cls
}
func newGoClosure(native Func, nups int) *Closure {
cls := &Closure{native: native}
if nups > 0 {
cls.upvals = make([]*upValue, nups)
}
return cls
}
func (x *Closure) Type() Type {
if x.isLua() {
return FuncType
}
return x.native.Type()
}
func (x *Closure) String() string {
return fmt.Sprintf("function: %p", x)
}
func (cls *Closure) isLua() bool { return cls != nil && cls.binary != nil }
func (cls *Closure) isGo() bool { return cls != nil && cls.native != nil }
func (cls *Closure) upvalues() []*upValue {
if cls != nil {
return cls.upvals
}
return nil
}
func (cls *Closure) getUp(index int) *upValue {
if cls != nil && index < len(cls.upvals) {
return cls.upvals[index]
}
return nil
}
func (cls *Closure) setUp(index int, value Value) {
if cls != nil && index < len(cls.upvals) {
cls.upvals[index].set(value)
}
}
func (cls *Closure) upName(index int) (name string) {
if cls.isLua() && index < len(cls.binary.UpNames) {
name = cls.binary.UpNames[index]
}
return
}
func (up *upValue) set(value Value) {
if up.open() {
up.frame.set(up.index, value)
return
}
up.value = value
}
func (up *upValue) get() Value {
if up.open() {
return up.frame.get(up.index)
}
return up.value
}
func (up *upValue) open() bool {
return up.index != -1
}
func (up *upValue) close() {
up.value = up.get()
up.index = -1
}