public static void AddCustomType(Type t, CustomReadDelegate reader, CustomWriteDelegate writer) { if (reader != null) { customReadDelegateMap[t] = reader; } if (writer != null) { customWriteDelegateMap[t] = writer; } }
//static bool IsDefaultValue(object o) //{ // Type t = o.GetType(); // if (!t.IsValueType) // return (o == null); // else // return o.Equals(Activator.CreateInstance(t)); //} public static LuaTable ToLua(LuaState ls, object o) { Type t = o.GetType(); if (t.GetCustomAttributes(typeof(NonSerializedAttribute), true).Length > 0) { return(null); } LuaTable result = null; if (o is IList) { Type listImplementation = t.GetInterface(typeof(IList <>).Name); if (listImplementation != null) { IList lst = o as IList; Type elemT = listImplementation.GetGenericArguments()[0]; if (!IsNoSerializeType(elemT)) { result = result ?? new LuaTable(ls); for (int i = 0; i < lst.Count; ++i) { object elem = lst[i]; if (elem == null) { continue; } if (IsBaseType(elemT)) { elem = ChangeType(elem, elemT); result[i + 1] = elem; } else { result[i + 1] = ToLua(ls, elem); } } } } } if (o is IDictionary) { Type dictImplementation = t.GetInterface(typeof(IDictionary <,>).Name); if (dictImplementation != null) { Type keyT = dictImplementation.GetGenericArguments()[0]; Type valueT = dictImplementation.GetGenericArguments()[1]; if (IsBaseType(keyT) && !IsNoSerializeType(valueT)) { result = result ?? new LuaTable(ls); IDictionary dict = o as IDictionary; var iter = dict.GetEnumerator(); while (iter.MoveNext()) { if (iter.Value == null) { continue; } if (iter.Key is string) { string stringKey = iter.Key as string; if (IsBaseType(valueT)) { object value = ChangeType(iter.Value, valueT); result[stringKey] = value; } else { result[stringKey] = ToLua(ls, iter.Value); } } else { int intKey = Convert.ToInt32(iter.Key); if (IsBaseType(valueT)) { object value = ChangeType(iter.Value, valueT); result[intKey] = value; } else { result[intKey] = ToLua(ls, iter.Value); } } } } } } if (!IsNoSerializeType(t)) { result = result ?? new LuaTable(ls); Type curT = t; while (curT != typeof(System.Object)) { var fis = curT.GetFields(System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.DeclaredOnly); for (int i = 0; i < fis.Length; ++i) { var fi = fis[i]; if (fi.GetCustomAttributes(typeof(NonSerializedAttribute), true).Length > 0) { continue; } Type elemT = fi.FieldType; object elem = fi.GetValue(o); if (elem == null) { continue; } if (IsBaseType(elemT)) { elem = ChangeType(elem, elemT); result[fi.Name] = elem; } else { result[fi.Name] = ToLua(ls, elem); } } CustomWriteDelegate writer = null; if (customWriteDelegateMap.TryGetValue(curT, out writer)) { writer(o, result); } curT = curT.BaseType; } } return(result); }