forked from layeh/gopher-luar
-
Notifications
You must be signed in to change notification settings - Fork 0
/
map.go
76 lines (64 loc) · 1.36 KB
/
map.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
package luar
import (
"reflect"
"github.com/yuin/gopher-lua"
)
func mapIndex(L *lua.LState) int {
ref, mt := check(L, 1)
key := L.CheckAny(2)
convertedKey, err := lValueToReflect(L, key, ref.Type().Key(), nil)
if err == nil {
item := ref.MapIndex(convertedKey)
if item.IsValid() {
L.Push(New(L, item.Interface()))
return 1
}
}
if lstring, ok := key.(lua.LString); ok {
if fn := mt.method(string(lstring)); fn != nil {
L.Push(fn)
return 1
}
}
return 0
}
func mapNewIndex(L *lua.LState) int {
ref, _ := check(L, 1)
key := L.CheckAny(2)
value := L.CheckAny(3)
keyHint := ref.Type().Key()
convertedKey, err := lValueToReflect(L, key, keyHint, nil)
if err != nil {
L.ArgError(2, err.Error())
}
var convertedValue reflect.Value
if value != lua.LNil {
convertedValue, err = lValueToReflect(L, value, ref.Type().Elem(), nil)
if err != nil {
L.ArgError(3, err.Error())
}
}
ref.SetMapIndex(convertedKey, convertedValue)
return 0
}
func mapLen(L *lua.LState) int {
ref, _ := check(L, 1)
L.Push(lua.LNumber(ref.Len()))
return 1
}
func mapCall(L *lua.LState) int {
ref, _ := check(L, 1)
keys := ref.MapKeys()
i := 0
fn := func(L *lua.LState) int {
if i >= len(keys) {
return 0
}
L.Push(New(L, keys[i].Interface()))
L.Push(New(L, ref.MapIndex(keys[i]).Interface()))
i++
return 2
}
L.Push(L.NewFunction(fn))
return 1
}