3

I'm making a small web-based RPG using Javascript, unfortunately once it came to implementing my saving and loading feature, a critical part of my code just failed completely.

As of now I'm saving all the player data in my player object:

var player = {
    stats: {
        level: 1,
        healthBase: 50,
        health: 50,
        strength: null,
        strengthBase: 7,
        strengthMods: {
        },
    },
};

Using these two functions:

function save() {
    localStorage.setItem("playerData", JSON.stringify(player));
}

function load() {
    player = JSON.parse(localStorage.getItem('playerData'));
}

This works perfectly for everything, except for one small part. In certain situations I need to add modifiers to my stats to change them, I do that like so

player.stats.strengthMods.mods = () => ( 5 );

However, if I save and then load my game, after calling

player.stats.strengthMods.mods

The console will only show me an empty object. I can't understand why my browser refuses to load the arrow function, everything else is loading perfectly apart from that.

Any idea why?

ShadowRanger
  • 143,180
  • 12
  • 188
  • 271
lpetrucci
  • 1,285
  • 4
  • 22
  • 40
  • JSON cannot serialize functions. – Brahma Dev Sep 27 '17 at 20:58
  • I don't get why you would want to save your modifiers that way. How is it any different from `player.stats.strengthMods.mods = [/* insert individual mods here*/]` with a separate, dedicated function for inserting and removing mods? –  Sep 27 '17 at 20:58
  • It's mostly depending on how they're then called and applied, I guess I'll have to make them your way if I want to save them – lpetrucci Sep 27 '17 at 21:00

1 Answers1

6

JSON doesn't have any way to store function definitions; it's a data serialization format, not an arbitrary object serialization format. Since you must JSONify to put the value in localStorage, you can't preserve functions. localStorage isn't the direct problem here; even if you never used it, the function wouldn't survive the round trip to JSON and back.

ShadowRanger
  • 143,180
  • 12
  • 188
  • 271