Stringy madness

So, I’m making a veeery basic level editor in html5 for LD.

“Ok, what’s the matter”, you could ask. Well, as you know, level editors “generally” needs to actually save the levels.

I tried some solutions and the localStorage API seemed to be  a easy win, except for one thing: it just works with strings!

My level editor saves all the objects on the level in a gigantic array. I just needed to save that array, but how?

Four steps:

 

  1. Convert every property in every object in the array to a string and save them in temporary objects in a temporary array.
  2. Convert every object on the temporary array to strings.
  3. Convert the array populated with strings into a string.
  4. Save the gigantic string on localStorage.

 

“Well, why not use JSON.stringify with the array” you may also ask. Well, because I was getting some “circular structure” errors, and I had no patience to figure out what was causing it.

“And why this is so mad” you may finally ask. Well, because a level (with only two tiles) looks something like this:

 

[“{\”x\”:\”240\”,\”y\”:\”192\”,\”cell\”:\”0,0\”,\”image\”:\”[object HTMLImageElement]\”,\”imgsrc\”:\”spritesheet.png\”,\”densidade\”:\”0\”,\”friccao\”:\”0\”,\”

elasticidade\”:\”0\”,\”tipo\”:\”static\”,\”collisiongroup\”:\”solid\”,\”forma\”:\”Quadrada\”}”,”{\”x\”:\”272\”,\”y\”:\”192\”,\”cell\”:\”0,0\”,\”image\”:\”[object HTMLImageElement]\”,\”imgsrc\”:\”spritesheet.png\”,\”densidade\”:\”0\”,\”friccao\”:\”0\”,

\”elasticidade\”:\”0\”,\”tipo\”:\”static\”,\”collisiongroup\”:\”solid\”,\”forma\”:\”Quadrada\”}”]

 

Well, there must be a more elegant way to do this…

 

Potatoes FTW!

Comments

22. Apr 2013 · 12:09 UTC
JSON (JavaScript Object Notation) is the answer to your question
22. Apr 2013 · 12:13 UTC
Another idea popped up in my head just now: strip the HTMLImage elements and only conserve the image path. Any element of the DOM tends to screw up JSON.