| 1 |
package luar |
| 2 |
|
| 3 |
import ( |
| 4 |
"fmt" |
| 5 |
"reflect" |
| 6 |
|
| 7 |
"github.com/yuin/gopher-lua" |
| 8 |
) |
| 9 |
|
| 10 |
// New creates and returns a new lua.LValue for the given value. Values are |
| 11 |
// converted in the following manner: |
| 12 |
// |
| 13 |
// A nil value (untyped, or a nil channel, function, map, pointer, or slice) is |
| 14 |
// converted to lua.LNil. |
| 15 |
// |
| 16 |
// A lua.LValue value is returned without conversion. |
| 17 |
// |
| 18 |
// Boolean values are converted to lua.LBool. |
| 19 |
// |
| 20 |
// String values are converted to lua.LString. |
| 21 |
// |
| 22 |
// Real numeric values (ints, uints, and floats) are converted to lua.LNumber. |
| 23 |
// |
| 24 |
// Functions are converted to *lua.LFunction. When called from Lua, Lua values |
| 25 |
// are converted to Go using the rules described in the package documentation, |
| 26 |
// and Go return values converted to Lua values using the rules described by |
| 27 |
// New. |
| 28 |
// |
| 29 |
// If a function has the signature: |
| 30 |
// func(*LState) int // *LState defined in this package, not in lua |
| 31 |
// The argument and return value conversions described above are skipped, and |
| 32 |
// the function is called with the arguments passed on the Lua stack. Return |
| 33 |
// values are pushed to the stack and the number of return values is returned |
| 34 |
// from the function. |
| 35 |
// |
| 36 |
// Arrays, channels, maps, pointers, slices, and structs are all converted to |
| 37 |
// *lua.LUserData with its Value field set to value. The userdata's metatable |
| 38 |
// is set to a table generated for value's type. The type's method set is |
| 39 |
// callable from the Lua type. If the type implements the fmt.Stringer |
| 40 |
// interface, that method will be used when the value is passed to the Lua |
| 41 |
// tostring function. |
| 42 |
// |
| 43 |
// With arrays, the # operator returns the array's length. Array elements can |
| 44 |
// be accessed with the index operator (array[index]). Calling an array |
| 45 |
// (array()) returns an iterator over the array that can be used in a for loop. |
| 46 |
// Two arrays of the same type can be compared for equality. Additionally, a |
| 47 |
// pointer to an array allows the array elements to be modified |
| 48 |
// (array[index] = value). |
| 49 |
// |
| 50 |
// With channels, the # operator returns the number of elements buffered in the |
| 51 |
// channel. Two channels of the same type can be compared for equality (i.e. if |
| 52 |
// they were created with the same make call). Calling a channel value with |
| 53 |
// no arguments reads one element from the channel, returning the value and a |
| 54 |
// boolean indicating if the channel is closed. Calling a channel value with |
| 55 |
// one argument sends the argument to the channel. The channel's unary minus |
| 56 |
// operator closes the channel (_ = -channel). |
| 57 |
// |
| 58 |
// With maps, the # operator returns the number of elements in the map. Map |
| 59 |
// elements can be accessed using the index operator (map[key]) and also set |
| 60 |
// (map[key] = value). Calling a map value returns an iterator over the map that |
| 61 |
// can be used in a for loop. If a map's key type is string, map values take |
| 62 |
// priority over methods. |
| 63 |
// |
| 64 |
// With slices, the # operator returns the length of the slice. Slice elements |
| 65 |
// can be accessed using the index operator (slice[index]) and also set |
| 66 |
// (slice[index] = value). Calling a slice returns an iterator over its elements |
| 67 |
// that can be used in a for loop. Elements can be appended to a slice using the |
| 68 |
// add operator (new_slice = slice + element). |
| 69 |
// |
| 70 |
// With structs, fields can be accessed using the index operator |
| 71 |
// (struct[field]). As a special case, accessing field that is an array or |
| 72 |
// struct field will return a pointer to that value. Structs of the same type |
| 73 |
// can be tested for equality. Additionally, a pointer to a struct can have its |
| 74 |
// fields set (struct[field] = value). |
| 75 |
// |
| 76 |
// Struct field accessibility can be changed by setting the field's luar tag. |
| 77 |
// If the tag is empty (default), the field is accessed by its name and its |
| 78 |
// name with a lowercase first letter (e.g. "Field1" would be accessible using |
| 79 |
// "Field1" or "field1"). If the tag is "-", the field will not be accessible. |
| 80 |
// Any other tag value makes the field accessible through that name. |
| 81 |
// |
| 82 |
// Pointer values can be compared for equality. The pointed to value can be |
| 83 |
// changed using the pow operator (pointer = pointer ^ value). A pointer can be |
| 84 |
// dereferenced using the unary minus operator (value = -pointer). |
| 85 |
// |
| 86 |
// All other values (complex numbers, unsafepointer, uintptr) are converted to |
| 87 |
// *lua.LUserData with its Value field set to value and no custom metatable. |
| 88 |
// |
| 89 |
func New(L *lua.LState, value interface{}) lua.LValue { |
| 90 |
if value == nil { |
| 91 |
return lua.LNil |
| 92 |
} |
| 93 |
if lval, ok := value.(lua.LValue); ok { |
| 94 |
return lval |
| 95 |
} |
| 96 |
|
| 97 |
switch val := reflect.ValueOf(value); val.Kind() { |
| 98 |
case reflect.Bool: |
| 99 |
return lua.LBool(val.Bool()) |
| 100 |
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: |
| 101 |
return lua.LNumber(float64(val.Int())) |
| 102 |
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64: |
| 103 |
return lua.LNumber(float64(val.Uint())) |
| 104 |
case reflect.Float32, reflect.Float64: |
| 105 |
return lua.LNumber(val.Float()) |
| 106 |
case reflect.Chan, reflect.Map, reflect.Ptr, reflect.Slice: |
| 107 |
if val.IsNil() { |
| 108 |
return lua.LNil |
| 109 |
} |
| 110 |
fallthrough |
| 111 |
case reflect.Array, reflect.Struct: |
| 112 |
ud := L.NewUserData() |
| 113 |
ud.Value = val.Interface() |
| 114 |
ud.Metatable = getMetatable(L, val.Type()) |
| 115 |
return ud |
| 116 |
case reflect.Func: |
| 117 |
if val.IsNil() { |
| 118 |
return lua.LNil |
| 119 |
} |
| 120 |
return funcWrapper(L, val, false) |
| 121 |
case reflect.String: |
| 122 |
return lua.LString(val.String()) |
| 123 |
default: |
| 124 |
ud := L.NewUserData() |
| 125 |
ud.Value = val.Interface() |
| 126 |
return ud |
| 127 |
} |
| 128 |
} |
| 129 |
|
| 130 |
// NewType returns a new type generator for the given value's type. |
| 131 |
// |
| 132 |
// When the returned lua.LValue is called, a new value will be created that is |
| 133 |
// dependent on value's type: |
| 134 |
// |
| 135 |
// If value is a channel, the first argument optionally specifies the channel's |
| 136 |
// buffer size (defaults to 1). The new channel is returned. |
| 137 |
// |
| 138 |
// If value is a map, a new map is returned. |
| 139 |
// |
| 140 |
// If value is a slice, the first argument optionally specifies the slices's |
| 141 |
// length (defaults to 0), and the second argument optionally specifies the |
| 142 |
// slice's capacity (defaults to the first argument). The new slice is returned. |
| 143 |
// |
| 144 |
// All other types return a new pointer to the zero value of value's type. |
| 145 |
func NewType(L *lua.LState, value interface{}) lua.LValue { |
| 146 |
val := reflect.TypeOf(value) |
| 147 |
ud := L.NewUserData() |
| 148 |
ud.Value = val |
| 149 |
ud.Metatable = getTypeMetatable(L, val) |
| 150 |
|
| 151 |
return ud |
| 152 |
} |
| 153 |
|
| 154 |
type conversionError struct { |
| 155 |
Lua lua.LValue |
| 156 |
Hint reflect.Type |
| 157 |
} |
| 158 |
|
| 159 |
func (c conversionError) Error() string { |
| 160 |
if _, isNil := c.Lua.(*lua.LNilType); isNil { |
| 161 |
return fmt.Sprintf("cannot use nil as type %s", c.Hint) |
| 162 |
} |
| 163 |
|
| 164 |
var val interface{} |
| 165 |
|
| 166 |
if userData, ok := c.Lua.(*lua.LUserData); ok { |
| 167 |
val = userData.Value |
| 168 |
} else { |
| 169 |
val = c.Lua |
| 170 |
} |
| 171 |
|
| 172 |
return fmt.Sprintf("cannot use %v (type %T) as type %s", val, val, c.Hint) |
| 173 |
} |
| 174 |
|
| 175 |
type structFieldError struct { |
| 176 |
Field string |
| 177 |
Type reflect.Type |
| 178 |
} |
| 179 |
|
| 180 |
func (s structFieldError) Error() string { |
| 181 |
return `type ` + s.Type.String() + ` has no field ` + s.Field |
| 182 |
} |
| 183 |
|
| 184 |
func lValueToReflect(L *lua.LState, v lua.LValue, hint reflect.Type, tryConvertPtr *bool) (reflect.Value, error) { |
| 185 |
visited := make(map[*lua.LTable]reflect.Value) |
| 186 |
return lValueToReflectInner(L, v, hint, visited, tryConvertPtr) |
| 187 |
} |
| 188 |
|
| 189 |
func lValueToReflectInner(L *lua.LState, v lua.LValue, hint reflect.Type, visited map[*lua.LTable]reflect.Value, tryConvertPtr *bool) (reflect.Value, error) { |
| 190 |
if hint.Implements(refTypeLuaLValue) { |
| 191 |
return reflect.ValueOf(v), nil |
| 192 |
} |
| 193 |
|
| 194 |
isPtr := false |
| 195 |
|
| 196 |
switch converted := v.(type) { |
| 197 |
case lua.LBool: |
| 198 |
val := reflect.ValueOf(bool(converted)) |
| 199 |
if !val.Type().ConvertibleTo(hint) { |
| 200 |
return reflect.Value{}, conversionError{ |
| 201 |
Lua: v, |
| 202 |
Hint: hint, |
| 203 |
} |
| 204 |
} |
| 205 |
return val.Convert(hint), nil |
| 206 |
case lua.LChannel: |
| 207 |
val := reflect.ValueOf(converted) |
| 208 |
if !val.Type().ConvertibleTo(hint) { |
| 209 |
return reflect.Value{}, conversionError{ |
| 210 |
Lua: v, |
| 211 |
Hint: hint, |
| 212 |
} |
| 213 |
} |
| 214 |
return val.Convert(hint), nil |
| 215 |
case lua.LNumber: |
| 216 |
val := reflect.ValueOf(float64(converted)) |
| 217 |
if !val.Type().ConvertibleTo(hint) { |
| 218 |
return reflect.Value{}, conversionError{ |
| 219 |
Lua: v, |
| 220 |
Hint: hint, |
| 221 |
} |
| 222 |
} |
| 223 |
return val.Convert(hint), nil |
| 224 |
case *lua.LFunction: |
| 225 |
emptyIfaceHint := false |
| 226 |
switch { |
| 227 |
case hint == refTypeEmptyIface: |
| 228 |
emptyIfaceHint = true |
| 229 |
inOut := []reflect.Type{ |
| 230 |
reflect.SliceOf(refTypeEmptyIface), |
| 231 |
} |
| 232 |
hint = reflect.FuncOf(inOut, inOut, true) |
| 233 |
case hint.Kind() != reflect.Func: |
| 234 |
return reflect.Value{}, conversionError{ |
| 235 |
Lua: v, |
| 236 |
Hint: hint, |
| 237 |
} |
| 238 |
} |
| 239 |
|
| 240 |
fn := func(args []reflect.Value) []reflect.Value { |
| 241 |
thread, cancelFunc := L.NewThread() |
| 242 |
defer thread.Close() |
| 243 |
if cancelFunc != nil { |
| 244 |
defer cancelFunc() |
| 245 |
} |
| 246 |
thread.Push(converted) |
| 247 |
defer thread.SetTop(0) |
| 248 |
|
| 249 |
argCount := 0 |
| 250 |
for i, arg := range args { |
| 251 |
if i+1 == len(args) && hint.IsVariadic() { |
| 252 |
// arg is a varadic slice |
| 253 |
for j := 0; j < arg.Len(); j++ { |
| 254 |
arg := arg.Index(j) |
| 255 |
thread.Push(New(thread, arg.Interface())) |
| 256 |
argCount++ |
| 257 |
} |
| 258 |
break |
| 259 |
} |
| 260 |
|
| 261 |
thread.Push(New(thread, arg.Interface())) |
| 262 |
argCount++ |
| 263 |
} |
| 264 |
|
| 265 |
thread.Call(argCount, lua.MultRet) |
| 266 |
top := thread.GetTop() |
| 267 |
|
| 268 |
switch { |
| 269 |
case emptyIfaceHint: |
| 270 |
ret := reflect.MakeSlice(reflect.SliceOf(refTypeEmptyIface), top, top) |
| 271 |
|
| 272 |
for i := 1; i <= top; i++ { |
| 273 |
item, err := lValueToReflect(thread, thread.Get(i), refTypeEmptyIface, nil) |
| 274 |
if err != nil { |
| 275 |
panic(err) |
| 276 |
} |
| 277 |
ret.Index(i - 1).Set(item) |
| 278 |
} |
| 279 |
|
| 280 |
return []reflect.Value{ret} |
| 281 |
|
| 282 |
case top == hint.NumOut(): |
| 283 |
ret := make([]reflect.Value, top) |
| 284 |
|
| 285 |
var err error |
| 286 |
for i := 1; i <= top; i++ { |
| 287 |
outHint := hint.Out(i - 1) |
| 288 |
item := thread.Get(i) |
| 289 |
ret[i-1], err = lValueToReflect(thread, item, outHint, nil) |
| 290 |
if err != nil { |
| 291 |
panic(err) |
| 292 |
} |
| 293 |
} |
| 294 |
|
| 295 |
return ret |
| 296 |
} |
| 297 |
|
| 298 |
panic(fmt.Errorf("expecting %d return values, got %d", hint.NumOut(), top)) |
| 299 |
} |
| 300 |
return reflect.MakeFunc(hint, fn), nil |
| 301 |
case *lua.LNilType: |
| 302 |
switch hint.Kind() { |
| 303 |
case reflect.Chan, reflect.Func, reflect.Interface, reflect.Map, reflect.Ptr, reflect.Slice, reflect.UnsafePointer, reflect.Uintptr: |
| 304 |
return reflect.Zero(hint), nil |
| 305 |
} |
| 306 |
|
| 307 |
return reflect.Value{}, conversionError{ |
| 308 |
Lua: v, |
| 309 |
Hint: hint, |
| 310 |
} |
| 311 |
|
| 312 |
case *lua.LState: |
| 313 |
val := reflect.ValueOf(converted) |
| 314 |
if !val.Type().ConvertibleTo(hint) { |
| 315 |
return reflect.Value{}, conversionError{ |
| 316 |
Lua: v, |
| 317 |
Hint: hint, |
| 318 |
} |
| 319 |
} |
| 320 |
return val.Convert(hint), nil |
| 321 |
|
| 322 |
case lua.LString: |
| 323 |
val := reflect.ValueOf(string(converted)) |
| 324 |
if !val.Type().ConvertibleTo(hint) { |
| 325 |
return reflect.Value{}, conversionError{ |
| 326 |
Lua: v, |
| 327 |
Hint: hint, |
| 328 |
} |
| 329 |
} |
| 330 |
return val.Convert(hint), nil |
| 331 |
|
| 332 |
case *lua.LTable: |
| 333 |
if existing := visited[converted]; existing.IsValid() { |
| 334 |
return existing, nil |
| 335 |
} |
| 336 |
|
| 337 |
if hint == refTypeEmptyIface { |
| 338 |
hint = reflect.MapOf(refTypeEmptyIface, refTypeEmptyIface) |
| 339 |
} |
| 340 |
|
| 341 |
switch { |
| 342 |
case hint.Kind() == reflect.Array: |
| 343 |
elemType := hint.Elem() |
| 344 |
length := converted.Len() |
| 345 |
if length != hint.Len() { |
| 346 |
return reflect.Value{}, conversionError{ |
| 347 |
Lua: v, |
| 348 |
Hint: hint, |
| 349 |
} |
| 350 |
} |
| 351 |
s := reflect.New(hint).Elem() |
| 352 |
visited[converted] = s |
| 353 |
|
| 354 |
for i := 0; i < length; i++ { |
| 355 |
value := converted.RawGetInt(i + 1) |
| 356 |
elemValue, err := lValueToReflectInner(L, value, elemType, visited, nil) |
| 357 |
if err != nil { |
| 358 |
return reflect.Value{}, err |
| 359 |
} |
| 360 |
s.Index(i).Set(elemValue) |
| 361 |
} |
| 362 |
|
| 363 |
return s, nil |
| 364 |
|
| 365 |
case hint.Kind() == reflect.Slice: |
| 366 |
elemType := hint.Elem() |
| 367 |
length := converted.Len() |
| 368 |
s := reflect.MakeSlice(hint, length, length) |
| 369 |
visited[converted] = s |
| 370 |
|
| 371 |
for i := 0; i < length; i++ { |
| 372 |
value := converted.RawGetInt(i + 1) |
| 373 |
elemValue, err := lValueToReflectInner(L, value, elemType, visited, nil) |
| 374 |
if err != nil { |
| 375 |
return reflect.Value{}, err |
| 376 |
} |
| 377 |
s.Index(i).Set(elemValue) |
| 378 |
} |
| 379 |
|
| 380 |
return s, nil |
| 381 |
|
| 382 |
case hint.Kind() == reflect.Map: |
| 383 |
keyType := hint.Key() |
| 384 |
elemType := hint.Elem() |
| 385 |
s := reflect.MakeMap(hint) |
| 386 |
visited[converted] = s |
| 387 |
|
| 388 |
for key := lua.LNil; ; { |
| 389 |
var value lua.LValue |
| 390 |
key, value = converted.Next(key) |
| 391 |
if key == lua.LNil { |
| 392 |
break |
| 393 |
} |
| 394 |
|
| 395 |
lKey, err := lValueToReflectInner(L, key, keyType, visited, nil) |
| 396 |
if err != nil { |
| 397 |
return reflect.Value{}, err |
| 398 |
} |
| 399 |
lValue, err := lValueToReflectInner(L, value, elemType, visited, nil) |
| 400 |
if err != nil { |
| 401 |
return reflect.Value{}, err |
| 402 |
} |
| 403 |
s.SetMapIndex(lKey, lValue) |
| 404 |
} |
| 405 |
|
| 406 |
return s, nil |
| 407 |
|
| 408 |
case hint.Kind() == reflect.Ptr && hint.Elem().Kind() == reflect.Struct: |
| 409 |
hint = hint.Elem() |
| 410 |
isPtr = true |
| 411 |
fallthrough |
| 412 |
case hint.Kind() == reflect.Struct: |
| 413 |
s := reflect.New(hint) |
| 414 |
visited[converted] = s |
| 415 |
|
| 416 |
t := s.Elem() |
| 417 |
|
| 418 |
mt := &Metatable{ |
| 419 |
LTable: getMetatable(L, hint), |
| 420 |
} |
| 421 |
|
| 422 |
for key := lua.LNil; ; { |
| 423 |
var value lua.LValue |
| 424 |
key, value = converted.Next(key) |
| 425 |
if key == lua.LNil { |
| 426 |
break |
| 427 |
} |
| 428 |
if _, ok := key.(lua.LString); !ok { |
| 429 |
continue |
| 430 |
} |
| 431 |
|
| 432 |
fieldName := key.String() |
| 433 |
index := mt.fieldIndex(fieldName) |
| 434 |
if index == nil { |
| 435 |
return reflect.Value{}, structFieldError{ |
| 436 |
Type: hint, |
| 437 |
Field: fieldName, |
| 438 |
} |
| 439 |
} |
| 440 |
field := hint.FieldByIndex(index) |
| 441 |
|
| 442 |
lValue, err := lValueToReflectInner(L, value, field.Type, visited, nil) |
| 443 |
if err != nil { |
| 444 |
return reflect.Value{}, nil |
| 445 |
} |
| 446 |
t.FieldByIndex(field.Index).Set(lValue) |
| 447 |
} |
| 448 |
|
| 449 |
if isPtr { |
| 450 |
return s, nil |
| 451 |
} |
| 452 |
|
| 453 |
return t, nil |
| 454 |
} |
| 455 |
|
| 456 |
return reflect.Value{}, conversionError{ |
| 457 |
Lua: v, |
| 458 |
Hint: hint, |
| 459 |
} |
| 460 |
|
| 461 |
case *lua.LUserData: |
| 462 |
val := reflect.ValueOf(converted.Value) |
| 463 |
if tryConvertPtr != nil && val.Kind() != reflect.Ptr && hint.Kind() == reflect.Ptr && val.Type() == hint.Elem() { |
| 464 |
newVal := reflect.New(hint.Elem()) |
| 465 |
newVal.Elem().Set(val) |
| 466 |
val = newVal |
| 467 |
*tryConvertPtr = true |
| 468 |
} else { |
| 469 |
if !val.Type().ConvertibleTo(hint) { |
| 470 |
return reflect.Value{}, conversionError{ |
| 471 |
Lua: converted, |
| 472 |
Hint: hint, |
| 473 |
} |
| 474 |
} |
| 475 |
val = val.Convert(hint) |
| 476 |
if tryConvertPtr != nil { |
| 477 |
*tryConvertPtr = false |
| 478 |
} |
| 479 |
} |
| 480 |
return val, nil |
| 481 |
} |
| 482 |
|
| 483 |
panic("never reaches") |
| 484 |
} |