@@ -29,36 +29,77 @@ func Loader(L *lua.LState) int {
2929var api = map [string ]lua.LGFunction {
3030 "decode" : apiDecode ,
3131 "encode" : apiEncode ,
32+ "array" : apiArray ,
3233}
3334
34- func apiDecode (L * lua.LState ) int {
35- str := L .CheckString (1 )
35+ func apiDecode (state * lua.LState ) int {
36+ str := state .CheckString (1 )
3637
37- value , err := Decode (L , []byte (str ))
38+ value , err := Decode (state , []byte (str ))
3839 if err != nil {
39- L .Push (lua .LNil )
40- L .Push (lua .LString (err .Error ()))
40+ state .Push (lua .LNil )
41+ state .Push (lua .LString (err .Error ()))
4142 return 2
4243 }
43- L .Push (value )
44+ state .Push (value )
4445 return 1
4546}
4647
47- func apiEncode (L * lua.LState ) int {
48- value := L .CheckAny (1 )
48+ func apiEncode (state * lua.LState ) int {
49+ value := state .CheckAny (1 )
4950
5051 data , err := Encode (value )
5152 if err != nil {
52- L .Push (lua .LNil )
53- L .RaiseError (err .Error ())
53+ state .Push (lua .LNil )
54+ state .RaiseError (err .Error ())
5455 return 1
5556 }
56- L .Push (lua .LString (string (data )))
57+ state .Push (lua .LString (string (data )))
5758 return 1
5859}
5960
6061// --------------------------------------------------------------------
6162
63+ // EmptyArray is a marker for an empty array.
64+ var EmptyArray = & lua.LUserData {Value : []any (nil )}
65+
66+ // apiArray creates an array from the arguments.
67+ func apiArray (state * lua.LState ) int {
68+ switch state .GetTop () {
69+ case 0 :
70+ state .Push (EmptyArray )
71+ return 1
72+ case 1 :
73+ // If it's not a table, or empty return a marker
74+ table , ok := state .CheckAny (1 ).(* lua.LTable )
75+ switch {
76+ case ok && table .Len () > 0 : // array
77+ state .Push (table )
78+ return 1
79+ case ok : // check if it's an empty map
80+ k , v := table .Next (lua .LNil )
81+ if k == lua .LNil && v == lua .LNil {
82+ state .Push (EmptyArray )
83+ return 1
84+ }
85+ }
86+
87+ // Otherwise, return an array
88+ fallthrough
89+ default :
90+ table := state .CreateTable (state .GetTop (), 0 )
91+ for i := 1 ; i <= state .GetTop (); i ++ {
92+ table .RawSetInt (i , state .Get (i ))
93+ }
94+
95+ // Return the table
96+ state .Push (table )
97+ return 1
98+ }
99+ }
100+
101+ // --------------------------------------------------------------------
102+
62103type invalidTypeError lua.LValueType
63104
64105func (i invalidTypeError ) Error () string {
@@ -87,7 +128,12 @@ func (j jsonValue) MarshalJSON() (data []byte, err error) {
87128 case * lua.LNilType :
88129 data = []byte (`null` )
89130 case * lua.LUserData :
90- data , err = json .Marshal (converted .Value )
131+ switch {
132+ case converted == EmptyArray :
133+ data = []byte (`[]` )
134+ default :
135+ data , err = json .Marshal (converted .Value )
136+ }
91137 case lua.LString :
92138 data , err = json .Marshal (string (converted ))
93139 case * lua.LTable :
0 commit comments