/*** Serialize(obj : object);* - Use this to JSON an object; AND preserve the data type.**/function Serialize(obj){ function Make(obj) { var o = { zztype: obj.constructor.name }; for (var i in obj) { if (!(obj[i] instanceof Array) && typeof obj[i] == "object") o[i] = Make(obj[i]); else o[i] = obj[i]; } return o; } return JSON.stringify(Make(obj));}/*** Deserialize(s : string);* - Use this to parse a JSON object; AND restore the methods.**/function Deserialize(s){ function Make(o) { var obj = new this[o.zztype](); for (var i in o) { if (!(o[i] instanceof Array) && o[i] typeof "object") obj[i] = Make(o[i]); else obj[i] = o[i]; } delete obj.zztype; return obj; } return Make(JSON.parse(s));}
function Item() { this.image = LoadImage("dagger.png"); // an image... which can't be saved to file... this.damage = 5; // this however can; even with JSON.}// but this method will be stripped during JSON creationItem.prototype.swing = function() { Print("Did " + this.damage + " damage!");}var item = new Item();item.damage += 2; // I upgraded it!!// serialization keeps an object, well the same object!var s = Serialize(item);File.save("item", s); // now I saved it to file!var o = File.recall("item", "");item = Deserialize(o);item.swing(); // prints "Did 7 damage!"item instanceof Item // returns true
var f = new Function("return new " + o.zztype + "();");var obj = f();
var obj = global[o.zztype]();
Code: [Select]var f = new Function("return new " + o.zztype + "();");var obj = f();Seems like it should just beCode: [Select]var obj = global[o.zztype]();
var obj = new this[o.zztype]();
Are you planning some sort of binary format, for instance to make save files harder to modify?
Edit: It doesn't work in Sphere. 'global' is not defined. I did some digging and found that the only way to access the global scope is by calling 'this' while in the global scope. So I changed the code to:Code: [Select]var obj = new this[o.zztype]();
And you are right about cyclic structures, but I don't use them often, and they aren't usually used for the kind of data that is intended to be saved, even though there might possibly a reason somewhere down the line.
Not really, my plan was to add an encode/decode layer to the final output string/bytearray.