-
Notifications
You must be signed in to change notification settings - Fork 55
/
luar.go
959 lines (880 loc) · 24.3 KB
/
luar.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
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
// Copyright (c) 2010-2016 Steve Donovan
package luar
import (
"errors"
"fmt"
"reflect"
"github.com/aarzilli/golua/lua"
)
// ConvError records a conversion error from value 'From' to value 'To'.
type ConvError struct {
From interface{}
To interface{}
}
// ErrTableConv arises when some table entries could not be converted.
// The table conversion result is usable.
// TODO: Work out a more relevant name.
// TODO: Should it be a type instead embedding the actual error?
var ErrTableConv = errors.New("some table elements could not be converted")
func (l ConvError) Error() string {
return fmt.Sprintf("cannot convert %v to %v", l.From, l.To)
}
// Lua 5.1 'lua_tostring' function only supports string and numbers. Extend it for internal purposes.
// From the Lua 5.3 source code.
func luaToString(L *lua.State, idx int) string {
switch L.Type(idx) {
case lua.LUA_TNUMBER:
L.PushValue(idx)
defer L.Pop(1)
return L.ToString(-1)
case lua.LUA_TSTRING:
return L.ToString(-1)
case lua.LUA_TBOOLEAN:
b := L.ToBoolean(idx)
if b {
return "true"
}
return "false"
case lua.LUA_TNIL:
return "nil"
}
return fmt.Sprintf("%s: %p", L.LTypename(idx), L.ToPointer(idx))
}
func luaDesc(L *lua.State, idx int) string {
return fmt.Sprintf("Lua value '%v' (%v)", luaToString(L, idx), L.LTypename(idx))
}
// NullT is the type of Null.
// Having a dedicated type allows us to make the distinction between zero values and Null.
type NullT int
// Map is an alias for map of strings.
type Map map[string]interface{}
var (
// Null is the definition of 'luar.null' which is used in place of 'nil' when
// converting slices and structs.
Null = NullT(0)
)
var (
tslice = typeof((*[]interface{})(nil))
tmap = typeof((*map[string]interface{})(nil))
nullv = reflect.ValueOf(Null)
)
// visitor holds the index to the table in LUA_REGISTRYINDEX with all the tables
// we ran across during a GoToLua conversion.
type visitor struct {
L *lua.State
index int
}
func newVisitor(L *lua.State) visitor {
var v visitor
v.L = L
v.L.NewTable()
v.index = v.L.Ref(lua.LUA_REGISTRYINDEX)
return v
}
func (v *visitor) close() {
v.L.Unref(lua.LUA_REGISTRYINDEX, v.index)
}
// Mark value on top of the stack as visited using the registry index.
func (v *visitor) mark(val reflect.Value) {
ptr := val.Pointer()
if ptr == 0 {
// We do not mark uninitialized 'val' as this is meaningless and this would
// bind all uninitialized values to the same mark.
return
}
v.L.RawGeti(lua.LUA_REGISTRYINDEX, v.index)
// Copy value on top.
v.L.PushValue(-2)
// Set value to table.
// TODO: Handle overflow.
v.L.RawSeti(-2, int(ptr))
v.L.Pop(1)
}
// Push visited value on top of the stack.
// If the value was not visited, return false and push nothing.
func (v *visitor) push(val reflect.Value) bool {
ptr := val.Pointer()
v.L.RawGeti(lua.LUA_REGISTRYINDEX, v.index)
v.L.RawGeti(-1, int(ptr))
if v.L.IsNil(-1) {
// Not visited.
v.L.Pop(2)
return false
}
v.L.Replace(-2)
return true
}
// Init makes and initializes a new pre-configured Lua state.
//
// It populates the 'luar' table with some helper functions/values:
//
// method: ProxyMethod
// unproxify: Unproxify
//
// chan: MakeChan
// complex: MakeComplex
// map: MakeMap
// slice: MakeSlice
//
// null: Null
//
// It replaces the 'pairs'/'ipairs' functions with ProxyPairs/ProxyIpairs
// respectively, so that __pairs/__ipairs can be used, Lua 5.2 style. It allows
// for looping over Go composite types and strings.
//
// It also replaces the 'type' function with ProxyType.
//
// It is not required for using the 'GoToLua' and 'LuaToGo' functions.
func Init() *lua.State {
var L = lua.NewState()
L.OpenLibs()
Register(L, "luar", Map{
// Functions.
"unproxify": Unproxify,
"method": ProxyMethod,
"chan": MakeChan,
"complex": Complex,
"map": MakeMap,
"slice": MakeSlice,
// Values.
"null": Null,
})
Register(L, "", Map{
"pairs": ProxyPairs,
"type": ProxyType,
})
// 'ipairs' needs a special case for performance reasons.
RegProxyIpairs(L, "", "ipairs")
return L
}
func isNil(v reflect.Value) bool {
nullables := [...]bool{
reflect.Chan: true,
reflect.Func: true,
reflect.Interface: true,
reflect.Map: true,
reflect.Ptr: true,
reflect.Slice: true,
}
kind := v.Type().Kind()
if int(kind) >= len(nullables) {
return false
}
return nullables[kind] && v.IsNil()
}
func copyMapToTable(L *lua.State, v reflect.Value, visited visitor) {
n := v.Len()
L.CreateTable(0, n)
visited.mark(v)
for _, key := range v.MapKeys() {
val := v.MapIndex(key)
goToLua(L, key, true, visited)
if isNil(val) {
val = nullv
}
goToLua(L, val, false, visited)
L.SetTable(-3)
}
}
// Also for arrays.
func copySliceToTable(L *lua.State, v reflect.Value, visited visitor) {
vp := v
for v.Kind() == reflect.Ptr {
// For arrays.
v = v.Elem()
}
n := v.Len()
L.CreateTable(n, 0)
if v.Kind() == reflect.Slice {
visited.mark(v)
} else if vp.Kind() == reflect.Ptr {
visited.mark(vp)
}
for i := 0; i < n; i++ {
L.PushInteger(int64(i + 1))
val := v.Index(i)
if isNil(val) {
val = nullv
}
goToLua(L, val, false, visited)
L.SetTable(-3)
}
}
func copyStructToTable(L *lua.State, v reflect.Value, visited visitor) {
// If 'vstruct' is a pointer to struct, use the pointer to mark as visited.
vp := v
for v.Kind() == reflect.Ptr {
v = v.Elem()
}
n := v.NumField()
L.CreateTable(n, 0)
if vp.Kind() == reflect.Ptr {
visited.mark(vp)
}
for i := 0; i < n; i++ {
st := v.Type()
field := st.Field(i)
key := field.Name
tag := field.Tag.Get("lua")
if tag != "" {
key = tag
}
goToLua(L, key, false, visited)
val := v.Field(i)
goToLua(L, val, false, visited)
L.SetTable(-3)
}
}
func callGoFunction(L *lua.State, v reflect.Value, args []reflect.Value) []reflect.Value {
defer func() {
if x := recover(); x != nil {
L.RaiseError(fmt.Sprintf("error %s", x))
}
}()
results := v.Call(args)
return results
}
func goToLuaFunction(L *lua.State, v reflect.Value) lua.LuaGoFunction {
switch f := v.Interface().(type) {
case func(*lua.State) int:
return f
}
t := v.Type()
argsT := make([]reflect.Type, t.NumIn())
for i := range argsT {
argsT[i] = t.In(i)
}
return func(L *lua.State) int {
var lastT reflect.Type
isVariadic := t.IsVariadic()
if isVariadic {
n := len(argsT)
lastT = argsT[n-1].Elem()
argsT = argsT[:n-1]
}
args := make([]reflect.Value, len(argsT))
for i, t := range argsT {
val := reflect.New(t)
err := LuaToGo(L, i+1, val.Interface())
if err != nil {
L.RaiseError(fmt.Sprintf("cannot convert Go function argument #%v: %v", i, err))
}
args[i] = val.Elem()
}
if isVariadic {
n := L.GetTop()
for i := len(argsT) + 1; i <= n; i++ {
val := reflect.New(lastT)
err := LuaToGo(L, i, val.Interface())
if err != nil {
L.RaiseError(fmt.Sprintf("cannot convert Go function argument #%v: %v", i, err))
}
args = append(args, val.Elem())
}
argsT = argsT[:len(argsT)+1]
}
results := callGoFunction(L, v, args)
for _, val := range results {
GoToLuaProxy(L, val)
}
return len(results)
}
}
// GoToLua pushes a Go value 'val' on the Lua stack.
//
// It unboxes interfaces.
//
// Pointers are followed recursively. Slices, structs and maps are copied over as tables.
func GoToLua(L *lua.State, a interface{}) {
visited := newVisitor(L)
goToLua(L, a, false, visited)
visited.close()
}
// GoToLuaProxy is like GoToLua but pushes a proxy on the Lua stack when it makes sense.
//
// A proxy is a Lua userdata that wraps a Go value.
//
// Proxies have several uses:
//
// - Type checking in Go function calls, so variable of user-defined type are
// always profixied.
//
// - Reflexive modification of the Go data straight from the Lua code. We only
// allow this for compound types.
//
// - Call methods of user-defined types.
//
// Predeclared scalar types are never proxified as they have no methods and we
// only allow compound types to be set reflexively.
//
// Structs are always proxified since their type is always user-defined. If they
// they are not settable (e.g. not nested, not passed by reference, value of a
// map), then a copy is passed as a proxy (otherwise setting the fields from Lua
// would panic). This will not impact the corresponding Go value.
//
// Arrays are only proxified if they are settable (so that the user can set the
// Go value from the Lua side) or if they are of a user-defined type (method
// calls or function parameters). If the type user-defined but the array is not
// settable, then a proxy of a copy is made, just as for structs.
//
// Lua cannot dereference pointers and Go can only call methods over one level
// of indirection at maximum. Thus proxies wrap around values dereferenced up to
// the last pointer.
//
// Go functions can be passed to Lua. If the parameters require several levels
// of indirections, the arguments will be converted automatically. Since proxies
// can only wrap around one level of indirection, functions modifying the value
// of the pointers after one level of indirection will have no effect.
func GoToLuaProxy(L *lua.State, a interface{}) {
visited := newVisitor(L)
goToLua(L, a, true, visited)
visited.close()
}
func goToLua(L *lua.State, a interface{}, proxify bool, visited visitor) {
var v reflect.Value
v, ok := a.(reflect.Value)
if !ok {
v = reflect.ValueOf(a)
}
if !v.IsValid() {
L.PushNil()
return
}
if v.Kind() == reflect.Interface && !v.IsNil() {
// Unbox interface.
v = reflect.ValueOf(v.Interface())
}
// Follow pointers if not proxifying. We save the parent pointer Value in case
// we proxify since Lua cannot dereference pointers and has no use of
// multiple-level references, while single references are useful for method
// calls functions that make use of one level of indirection.
vp := v
for v.Kind() == reflect.Ptr {
vp = v
v = v.Elem()
}
if !v.IsValid() {
L.PushNil()
return
}
// As a special case, we always proxify Null, the empty element for slices and maps.
if v.CanInterface() && v.Interface() == Null {
makeValueProxy(L, v, cInterfaceMeta)
return
}
switch v.Kind() {
case reflect.Float64, reflect.Float32:
if proxify && isNewType(v.Type()) {
makeValueProxy(L, vp, cNumberMeta)
} else {
L.PushNumber(v.Float())
}
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
if proxify && isNewType(v.Type()) {
makeValueProxy(L, vp, cNumberMeta)
} else {
L.PushNumber(float64(v.Int()))
}
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
if proxify && isNewType(v.Type()) {
makeValueProxy(L, vp, cNumberMeta)
} else {
L.PushNumber(float64(v.Uint()))
}
case reflect.String:
if proxify && isNewType(v.Type()) {
makeValueProxy(L, vp, cStringMeta)
} else {
L.PushString(v.String())
}
case reflect.Bool:
if proxify && isNewType(v.Type()) {
makeValueProxy(L, vp, cInterfaceMeta)
} else {
L.PushBoolean(v.Bool())
}
case reflect.Complex128, reflect.Complex64:
makeValueProxy(L, vp, cComplexMeta)
case reflect.Array:
if proxify {
// To check if it is a user-defined type, we compare its type to that of a
// new go array with the same length and the same element type.
vRawType := reflect.ArrayOf(v.Type().Len(), v.Type().Elem())
if vRawType != v.Type() || v.CanSet() {
if !v.CanSet() {
vp = reflect.New(v.Type())
reflect.Copy(vp.Elem(), v)
// 'vp' is a pointer of v.Type(), we want the dereferenced type.
vp = vp.Elem()
}
makeValueProxy(L, vp, cSliceMeta)
return
}
// Else don't proxify.
}
// See the case of struct.
if vp.Kind() == reflect.Ptr && visited.push(vp) {
return
}
copySliceToTable(L, vp, visited)
case reflect.Slice:
if proxify {
makeValueProxy(L, vp, cSliceMeta)
} else {
if visited.push(v) {
return
}
copySliceToTable(L, v, visited)
}
case reflect.Map:
if proxify {
makeValueProxy(L, vp, cMapMeta)
} else {
if visited.push(v) {
return
}
copyMapToTable(L, v, visited)
}
case reflect.Struct:
if proxify {
if vp.CanInterface() {
switch v := vp.Interface().(type) {
case error:
// TODO: Test proxification of errors.
L.PushString(v.Error())
return
case *LuaObject:
// TODO: Move out of 'proxify' condition? LuaObject is meant to be
// manipulated from the Go side, it is not useful in Lua.
if v.l == L {
v.Push()
} else {
// TODO: What shall we do when LuaObject state is not the current
// state? Copy across states? Is it always possible?
L.PushNil()
}
return
default:
}
}
// Structs are always user-defined types, so it makes sense to always
// proxify them.
if !v.CanSet() {
vp = reflect.New(v.Type())
vp.Elem().Set(v)
}
makeValueProxy(L, vp, cStructMeta)
} else {
// Use vp instead of v to detect cycles from the very first element, if a pointer.
if vp.Kind() == reflect.Ptr && visited.push(vp) {
return
}
copyStructToTable(L, vp, visited)
}
case reflect.Chan:
makeValueProxy(L, vp, cChannelMeta)
case reflect.Func:
L.PushGoFunction(goToLuaFunction(L, v))
default:
if val, ok := v.Interface().(error); ok {
L.PushString(val.Error())
} else if v.IsNil() {
L.PushNil()
} else {
makeValueProxy(L, vp, cInterfaceMeta)
}
}
}
func luaIsEmpty(L *lua.State, idx int) bool {
L.PushNil()
if idx < 0 {
idx--
}
if L.Next(idx) != 0 {
L.Pop(2)
return false
}
return true
}
func luaMapLen(L *lua.State, idx int) int {
L.PushNil()
if idx < 0 {
idx--
}
len := 0
for L.Next(idx) != 0 {
len++
L.Pop(1)
}
return len
}
func copyTableToMap(L *lua.State, idx int, v reflect.Value, visited map[uintptr]reflect.Value) (status error) {
t := v.Type()
if v.IsNil() {
v.Set(reflect.MakeMap(t))
}
te, tk := t.Elem(), t.Key()
// See copyTableToSlice.
ptr := L.ToPointer(idx)
if !luaIsEmpty(L, idx) {
visited[ptr] = v
}
L.PushNil()
if idx < 0 {
idx--
}
for L.Next(idx) != 0 {
// key at -2, value at -1
key := reflect.New(tk).Elem()
err := luaToGo(L, -2, key, visited)
if err != nil {
status = ErrTableConv
L.Pop(1)
continue
}
val := reflect.New(te).Elem()
err = luaToGo(L, -1, val, visited)
if err != nil {
status = ErrTableConv
L.Pop(1)
continue
}
v.SetMapIndex(key, val)
L.Pop(1)
}
return
}
// Also for arrays. TODO: Create special function for arrays?
func copyTableToSlice(L *lua.State, idx int, v reflect.Value, visited map[uintptr]reflect.Value) (status error) {
t := v.Type()
n := int(L.ObjLen(idx))
// Adjust the length of the array/slice.
if n > v.Len() {
if t.Kind() == reflect.Array {
n = v.Len()
} else {
// Slice
v.Set(reflect.MakeSlice(t, n, n))
}
} else if n < v.Len() {
if t.Kind() == reflect.Array {
// Nullify remaining elements.
for i := n; i < v.Len(); i++ {
v.Index(i).Set(reflect.Zero(t.Elem()))
}
} else {
// Slice
v.SetLen(n)
}
}
// Do not add empty slices to the list of visited elements.
// The empty Lua table is a single instance object and gets re-used across maps, slices and others.
// Arrays cannot be cyclic since the interface type will ask for slices.
if n > 0 && t.Kind() != reflect.Array {
ptr := L.ToPointer(idx)
visited[ptr] = v
}
te := t.Elem()
for i := 1; i <= n; i++ {
L.RawGeti(idx, i)
val := reflect.New(te).Elem()
err := luaToGo(L, -1, val, visited)
if err != nil {
status = ErrTableConv
L.Pop(1)
continue
}
v.Index(i - 1).Set(val)
L.Pop(1)
}
return
}
func copyTableToStruct(L *lua.State, idx int, v reflect.Value, visited map[uintptr]reflect.Value) (status error) {
t := v.Type()
// See copyTableToSlice.
ptr := L.ToPointer(idx)
if !luaIsEmpty(L, idx) {
visited[ptr] = v.Addr()
}
// Associate Lua keys with Go fields: tags have priority over matching field
// name.
fields := map[string]string{}
for i := 0; i < v.NumField(); i++ {
field := t.Field(i)
tag := field.Tag.Get("lua")
if tag != "" {
fields[tag] = field.Name
continue
}
fields[field.Name] = field.Name
}
L.PushNil()
if idx < 0 {
idx--
}
for L.Next(idx) != 0 {
L.PushValue(-2)
// Warning: ToString changes the value on stack.
key := L.ToString(-1)
L.Pop(1)
f := v.FieldByName(fields[key])
if f.CanSet() {
val := reflect.New(f.Type()).Elem()
err := luaToGo(L, -1, val, visited)
if err != nil {
status = ErrTableConv
L.Pop(1)
continue
}
f.Set(val)
}
L.Pop(1)
}
return
}
// LuaToGo converts the Lua value at index 'idx' to the Go value.
//
// The Go value must be a non-nil pointer.
//
// Conversions to strings and numbers are straightforward.
//
// Lua 'nil' is converted to the zero value of the specified Go value.
//
// If the Lua value is non-nil, pointers are dereferenced (multiple times if
// required) and the pointed value is the one that is set. If 'nil', then the Go
// pointer is set to 'nil'. To set a pointer's value to its zero value, use
// 'luar.null'.
//
// The Go value can be an interface, in which case the type is inferred. When
// converting a table to an interface, the Go value is a []interface{} slice if
// all its elements are indexed consecutively from 1, or a
// map[string]interface{} otherwise.
//
// Existing entries in maps and structs are kept. Arrays and slices are reset.
//
// Nil maps and slices are automatically allocated.
//
// Proxies are unwrapped to the Go value, if convertible. If both the proxy and
// the Go value are pointers, then the Go pointer will be set to the proxy
// pointer.
// Userdata that is not a proxy will be converted to a LuaObject if the Go value
// is an interface or a LuaObject.
func LuaToGo(L *lua.State, idx int, a interface{}) error {
// LuaToGo should not pop the Lua stack to be consistent with L.ToString(), etc.
// It is also easier in practice when we want to keep working with the value on stack.
v := reflect.ValueOf(a)
// TODO: Test interfaces with methods.
// TODO: Allow unreferenced map? encoding/json does not do it.
if v.Kind() != reflect.Ptr {
return errors.New("not a pointer")
}
if v.IsNil() {
return errors.New("nil pointer")
}
v = v.Elem()
// If the Lua value is 'nil' and the Go value is a pointer, nullify the pointer.
if v.Kind() == reflect.Ptr && L.IsNil(idx) {
v.Set(reflect.Zero(v.Type()))
return nil
}
return luaToGo(L, idx, v, map[uintptr]reflect.Value{})
}
func luaToGo(L *lua.State, idx int, v reflect.Value, visited map[uintptr]reflect.Value) error {
// Derefence 'v' until a non-pointer.
// This initializes the values, which will be useless effort if the conversion
// fails.
// This must be done here and not in LuaToGo so that the copyTable* functions
// can also call luaToGo on pointers.
vp := v
for v.Kind() == reflect.Ptr {
if v.IsNil() {
v.Set(reflect.New(v.Type().Elem()))
}
vp = v
v = v.Elem()
}
kind := v.Kind()
switch L.Type(idx) {
case lua.LUA_TNIL:
v.Set(reflect.Zero(v.Type()))
case lua.LUA_TBOOLEAN:
if kind != reflect.Bool && kind != reflect.Interface {
return ConvError{From: luaDesc(L, idx), To: v.Type()}
}
v.Set(reflect.ValueOf(L.ToBoolean(idx)))
case lua.LUA_TNUMBER:
switch k := unsizedKind(v); k {
case reflect.Int64, reflect.Uint64, reflect.Float64, reflect.Interface:
// We do not use ToInteger as it may truncate the value. Let Go truncate
// instead in Convert().
f := reflect.ValueOf(L.ToNumber(idx))
v.Set(f.Convert(v.Type()))
case reflect.Complex128:
v.SetComplex(complex(L.ToNumber(idx), 0))
default:
return ConvError{From: luaDesc(L, idx), To: v.Type()}
}
case lua.LUA_TSTRING:
if kind != reflect.String && kind != reflect.Interface {
return ConvError{From: luaDesc(L, idx), To: v.Type()}
}
v.Set(reflect.ValueOf(L.ToString(idx)))
case lua.LUA_TUSERDATA:
if isValueProxy(L, idx) {
val, typ := valueOfProxy(L, idx)
if val.Interface() == Null {
// Special case for Null.
v.Set(reflect.Zero(v.Type()))
return nil
}
// If both 'val' and 'v' are pointers, set the 'val' pointer to 'v'.
if typ.ConvertibleTo(vp.Type()) {
vp.Set(val.Convert(vp.Type()))
return nil
}
// Otherwise dereference.
for !typ.ConvertibleTo(v.Type()) && val.Kind() == reflect.Ptr {
val = val.Elem()
typ = typ.Elem()
}
if !typ.ConvertibleTo(v.Type()) {
return ConvError{From: fmt.Sprintf("proxy (%v)", typ), To: v.Type()}
}
// We automatically convert between types. This behaviour is consistent
// with LuaToGo conversions elsewhere.
v.Set(val.Convert(v.Type()))
return nil
} else if kind != reflect.Interface || v.Type() != reflect.TypeOf(LuaObject{}) {
return ConvError{From: luaDesc(L, idx), To: v.Type()}
}
// Wrap the userdata into a LuaObject.
v.Set(reflect.ValueOf(NewLuaObject(L, idx)))
case lua.LUA_TTABLE:
// If several Lua objects point to the same value while they map to Go
// values of different types, 'visited' should be skipped. Since such a
// condition is hard to infere, we simply check if it is convertible.
//
// Lua source:
// t = {
// names = {"foo", "bar"},
// altnames = names,
// }
//
// Go target:
// t := struct {
// names: []string
// altnames: map[string]string
// }
ptr := L.ToPointer(idx)
if val, ok := visited[ptr]; ok {
if v.Kind() == reflect.Struct && val.Type().ConvertibleTo(vp.Type()) {
vp.Set(val)
return nil
} else if val.Type().ConvertibleTo(v.Type()) {
v.Set(val)
return nil
}
}
switch kind {
case reflect.Array:
fallthrough
case reflect.Slice:
return copyTableToSlice(L, idx, v, visited)
case reflect.Map:
return copyTableToMap(L, idx, v, visited)
case reflect.Struct:
return copyTableToStruct(L, idx, v, visited)
case reflect.Interface:
n := int(L.ObjLen(idx))
switch v.Elem().Kind() {
case reflect.Map:
return copyTableToMap(L, idx, v.Elem(), visited)
case reflect.Slice:
// Need to make/resize the slice here since interface values are not adressable.
v.Set(reflect.MakeSlice(v.Elem().Type(), n, n))
return copyTableToSlice(L, idx, v.Elem(), visited)
}
if luaMapLen(L, idx) != n {
v.Set(reflect.MakeMap(tmap))
return copyTableToMap(L, idx, v.Elem(), visited)
}
v.Set(reflect.MakeSlice(tslice, n, n))
return copyTableToSlice(L, idx, v.Elem(), visited)
default:
return ConvError{From: luaDesc(L, idx), To: v.Type()}
}
case lua.LUA_TFUNCTION:
if kind == reflect.Interface {
v.Set(reflect.ValueOf(NewLuaObject(L, idx)))
} else if vp.Type() == reflect.TypeOf(&LuaObject{}) {
vp.Set(reflect.ValueOf(NewLuaObject(L, idx)))
} else {
return ConvError{From: luaDesc(L, idx), To: v.Type()}
}
default:
return ConvError{From: luaDesc(L, idx), To: v.Type()}
}
return nil
}
func isNewType(t reflect.Type) bool {
types := [...]reflect.Type{
reflect.Invalid: nil, // Invalid Kind = iota
reflect.Bool: typeof((*bool)(nil)),
reflect.Int: typeof((*int)(nil)),
reflect.Int8: typeof((*int8)(nil)),
reflect.Int16: typeof((*int16)(nil)),
reflect.Int32: typeof((*int32)(nil)),
reflect.Int64: typeof((*int64)(nil)),
reflect.Uint: typeof((*uint)(nil)),
reflect.Uint8: typeof((*uint8)(nil)),
reflect.Uint16: typeof((*uint16)(nil)),
reflect.Uint32: typeof((*uint32)(nil)),
reflect.Uint64: typeof((*uint64)(nil)),
reflect.Uintptr: typeof((*uintptr)(nil)),
reflect.Float32: typeof((*float32)(nil)),
reflect.Float64: typeof((*float64)(nil)),
reflect.Complex64: typeof((*complex64)(nil)),
reflect.Complex128: typeof((*complex128)(nil)),
reflect.String: typeof((*string)(nil)),
}
pt := types[int(t.Kind())]
return pt != t
}
// Register makes a number of Go values available in Lua code as proxies.
// 'values' is a map of strings to Go values.
//
// - If table is non-nil, then create or reuse a global table of that name and
// put the values in it.
//
// - If table is '' then put the values in the global table (_G).
//
// - If table is '*' then assume that the table is already on the stack.
//
// See GoToLuaProxy's documentation.
func Register(L *lua.State, table string, values Map) {
pop := true
if table == "*" {
pop = false
} else if len(table) > 0 {
L.GetGlobal(table)
if L.IsNil(-1) {
L.Pop(1)
L.NewTable()
L.SetGlobal(table)
L.GetGlobal(table)
}
} else {
L.GetGlobal("_G")
}
for name, val := range values {
GoToLuaProxy(L, val)
L.SetField(-2, name)
}
if pop {
L.Pop(1)
}
}
// Closest we'll get to a typeof operator.
func typeof(a interface{}) reflect.Type {
return reflect.TypeOf(a).Elem()
}