diff --git a/utility.go b/utility.go new file mode 100644 index 0000000..a04c28a --- /dev/null +++ b/utility.go @@ -0,0 +1,68 @@ +// Package lua ... +// +// Description : lua ... +// +// Author : go_developer@163.com<白茶清欢> +// +// Date : 2025-05-13 14:50 +package lua + +import "reflect" + +// Map2ScriptParam map每一项转换为脚本参数 +func Map2ScriptParam(inputMap map[string]any) []ScriptParam { + res := make([]ScriptParam, 0) + for k, v := range inputMap { + res = append(res, ScriptParam{ + Name: k, + Value: v, + }) + } + return res +} + +// Any2ScriptParam struct每一项转换为脚本参数 +// 仅支持 map / struct / *struct +func Any2ScriptParam(input any) []ScriptParam { + res := make([]ScriptParam, 0) + + if nil == input { + return res + } + dataVal := reflect.ValueOf(input) + if dataVal.IsNil() { + return res + } + dataType := reflect.TypeOf(input) + if dataType.Kind() == reflect.Ptr { + dataType = dataType.Elem() + dataVal = dataVal.Elem() + } + if dataType.Kind() == reflect.Map { + for _, key := range dataVal.MapKeys() { + res = append(res, ScriptParam{ + Name: key.String(), + Value: dataVal.MapIndex(key).Interface(), + }) + } + return res + } + + if dataType.Kind() == reflect.Struct { + for i := 0; i < dataType.NumField(); i++ { + paramName := dataType.Field(i).Name + jsonTag := dataType.Field(i).Tag.Get("json") + if jsonTag == "-" { + continue + } + if jsonTag != "" { + paramName = jsonTag + } + res = append(res, ScriptParam{ + Name: paramName, + Value: dataVal.Field(i).Interface(), + }) + } + } + return res +}