github.com/hirochachacha/plua@v0.0.0-20170217012138-c82f520cc725/object/reflect/complex.go (about) 1 package reflect 2 3 import ( 4 "fmt" 5 "reflect" 6 7 "github.com/hirochachacha/plua/internal/tables" 8 "github.com/hirochachacha/plua/object" 9 "github.com/hirochachacha/plua/object/fnutil" 10 ) 11 12 func buildComplexMT() { 13 mt := tables.NewTableSize(0, 9) 14 15 mt.Set(object.TM_METATABLE, object.True) 16 mt.Set(object.TM_NAME, object.String("COMPLEX*")) 17 mt.Set(object.TM_TOSTRING, tostring(toComplex)) 18 mt.Set(object.TM_INDEX, index(toComplex)) 19 20 mt.Set(object.TM_EQ, cmp(func(x, y reflect.Value) bool { return x.Complex() == y.Complex() }, toComplex)) 21 22 mt.Set(object.TM_UNM, unary(func(x reflect.Value) reflect.Value { return reflect.ValueOf(-x.Complex()) }, toComplex, mt)) 23 24 mt.Set(object.TM_ADD, binary(func(x, y reflect.Value) (reflect.Value, *object.RuntimeError) { 25 return reflect.ValueOf(x.Complex() + y.Complex()), nil 26 }, toComplex, mt)) 27 mt.Set(object.TM_SUB, binary(func(x, y reflect.Value) (reflect.Value, *object.RuntimeError) { 28 return reflect.ValueOf(x.Complex() - y.Complex()), nil 29 }, toComplex, mt)) 30 mt.Set(object.TM_MUL, binary(func(x, y reflect.Value) (reflect.Value, *object.RuntimeError) { 31 return reflect.ValueOf(x.Complex() * y.Complex()), nil 32 }, toComplex, mt)) 33 mt.Set(object.TM_DIV, binary(func(x, y reflect.Value) (reflect.Value, *object.RuntimeError) { 34 return reflect.ValueOf(x.Complex() / y.Complex()), nil 35 }, toComplex, mt)) 36 37 complexMT = mt 38 } 39 40 func toComplex(ap *fnutil.ArgParser, n int) (reflect.Value, *object.RuntimeError) { 41 val, err := toValue(ap, n, "COMPLEX*") 42 if err != nil { 43 return reflect.Value{}, err 44 } 45 switch val.Kind() { 46 case reflect.Complex64, reflect.Complex128: 47 default: 48 return reflect.Value{}, ap.TypeError(n, "COMPLEX*") 49 } 50 return val, nil 51 } 52 53 func cmtostring(th object.Thread, args ...object.Value) ([]object.Value, *object.RuntimeError) { 54 ap := fnutil.NewArgParser(th, args) 55 56 f, err := toComplex(ap, 0) 57 if err != nil { 58 return nil, err 59 } 60 61 return []object.Value{object.String(fmt.Sprintf("%v", f))}, nil 62 }