forked from layeh/gopher-luar
-
Notifications
You must be signed in to change notification settings - Fork 0
/
struct.go
97 lines (81 loc) · 1.81 KB
/
struct.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
package luar
import (
"reflect"
"github.com/yuin/gopher-lua"
)
func structIndex(L *lua.LState) int {
ref, mt := check(L, 1)
key := L.CheckString(2)
if fn := mt.method(key); fn != nil {
L.Push(fn)
return 1
}
ref = reflect.Indirect(ref)
index := mt.fieldIndex(key)
if index == nil {
return 0
}
field := ref.FieldByIndex(index)
if !field.CanInterface() {
L.RaiseError("cannot interface field " + key)
}
if (field.Kind() == reflect.Struct || field.Kind() == reflect.Array) && field.CanAddr() {
field = field.Addr()
}
L.Push(New(L, field.Interface()))
return 1
}
func structPtrIndex(L *lua.LState) int {
ref, mt := check(L, 1)
key := L.CheckString(2)
if fn := mt.method(key); fn != nil {
L.Push(fn)
return 1
}
ref = ref.Elem()
mt = MT(L, ref.Interface())
if fn := mt.method(key); fn != nil {
L.Push(fn)
return 1
}
index := mt.fieldIndex(key)
if index == nil {
return 0
}
field := ref.FieldByIndex(index)
if !field.CanInterface() {
L.RaiseError("cannot interface field " + key)
}
if (field.Kind() == reflect.Struct || field.Kind() == reflect.Array) && field.CanAddr() {
field = field.Addr()
}
L.Push(New(L, field.Interface()))
return 1
}
func structPtrNewIndex(L *lua.LState) int {
ref, mt := check(L, 1)
key := L.CheckString(2)
value := L.CheckAny(3)
ref = ref.Elem()
mt = MT(L, ref.Interface())
index := mt.fieldIndex(key)
if index == nil {
L.RaiseError("unknown field " + key)
}
field := ref.FieldByIndex(index)
if !field.CanSet() {
L.RaiseError("cannot set field " + key)
}
val, err := lValueToReflect(L, value, field.Type(), nil)
if err != nil {
L.ArgError(2, err.Error())
}
field.Set(val)
return 0
}
func structEq(L *lua.LState) int {
ref1, _ := check(L, 1)
ref2, _ := check(L, 2)
L.Push(lua.LBool(ref1.Interface() == ref2.Interface()))
return 1
}