| 1 |
package luar |
| 2 |
|
| 3 |
import ( |
| 4 |
"reflect" |
| 5 |
|
| 6 |
"github.com/yuin/gopher-lua" |
| 7 |
) |
| 8 |
|
| 9 |
func mapIndex(L *lua.LState) int { |
| 10 |
ref, mt := check(L, 1) |
| 11 |
key := L.CheckAny(2) |
| 12 |
|
| 13 |
convertedKey, err := lValueToReflect(L, key, ref.Type().Key(), nil) |
| 14 |
if err == nil { |
| 15 |
item := ref.MapIndex(convertedKey) |
| 16 |
if item.IsValid() { |
| 17 |
L.Push(New(L, item.Interface())) |
| 18 |
return 1 |
| 19 |
} |
| 20 |
} |
| 21 |
|
| 22 |
if lstring, ok := key.(lua.LString); ok { |
| 23 |
if fn := mt.method(string(lstring)); fn != nil { |
| 24 |
L.Push(fn) |
| 25 |
return 1 |
| 26 |
} |
| 27 |
} |
| 28 |
|
| 29 |
return 0 |
| 30 |
} |
| 31 |
|
| 32 |
func mapNewIndex(L *lua.LState) int { |
| 33 |
ref, _ := check(L, 1) |
| 34 |
key := L.CheckAny(2) |
| 35 |
value := L.CheckAny(3) |
| 36 |
|
| 37 |
keyHint := ref.Type().Key() |
| 38 |
convertedKey, err := lValueToReflect(L, key, keyHint, nil) |
| 39 |
if err != nil { |
| 40 |
L.ArgError(2, err.Error()) |
| 41 |
} |
| 42 |
var convertedValue reflect.Value |
| 43 |
if value != lua.LNil { |
| 44 |
convertedValue, err = lValueToReflect(L, value, ref.Type().Elem(), nil) |
| 45 |
if err != nil { |
| 46 |
L.ArgError(3, err.Error()) |
| 47 |
} |
| 48 |
} |
| 49 |
ref.SetMapIndex(convertedKey, convertedValue) |
| 50 |
return 0 |
| 51 |
} |
| 52 |
|
| 53 |
func mapLen(L *lua.LState) int { |
| 54 |
ref, _ := check(L, 1) |
| 55 |
|
| 56 |
L.Push(lua.LNumber(ref.Len())) |
| 57 |
return 1 |
| 58 |
} |
| 59 |
|
| 60 |
func mapCall(L *lua.LState) int { |
| 61 |
ref, _ := check(L, 1) |
| 62 |
|
| 63 |
keys := ref.MapKeys() |
| 64 |
i := 0 |
| 65 |
fn := func(L *lua.LState) int { |
| 66 |
if i >= len(keys) { |
| 67 |
return 0 |
| 68 |
} |
| 69 |
L.Push(New(L, keys[i].Interface())) |
| 70 |
L.Push(New(L, ref.MapIndex(keys[i]).Interface())) |
| 71 |
i++ |
| 72 |
return 2 |
| 73 |
} |
| 74 |
L.Push(L.NewFunction(fn)) |
| 75 |
return 1 |
| 76 |
} |