keys registered through SaveAPI.add
Add new keys to the storage (localStorage by default) and set them to
the given default values if they do not exist.
key and corresponding values
this namespace, typed with the keys just registered, so they can be read back without a cast
Make a storage for setStorage() out of a platform's cloud save, such as YouTube Playables' or Facebook Instant Games': the save is loaded once, before the game starts, and everything is saved back in one piece.
data is what the platform loaded: an object, or that object in JSON,
or nothing the first time. The storage starts from it and keeps every
item in memory, so save reads and writes without waiting.write(items) saves every item back to the platform. Changes made
together are saved in one call, and calls are made one at a time:
changes made while one is in progress go in the next one, with the
latest values. A platform that refuses a save while another is
pending, as Facebook's does, never sees two.flush().flush() saves at once and resolves when everything is saved: call it
when the platform pauses or closes the game.what the platform loaded, and how to save
the storage, to hand to setStorage()
Keep the saved keys somewhere other than the browser's localStorage,
the default: a game portal's cloud save, for example, or the storage of
a native wrapper. storage is anything with the getItem, setItem
and removeItem methods of the Web Storage API (see
SaveStorage), which save calls as it calls localStorage's,
so save.setStorage(localStorage) goes back to the default.
add().localStorage's are. For a cloud save,
which loads and saves asynchronously, use
createCloudStorage(): it holds
the items in memory once they are loaded, and saves in the background.where the keys are kept from now on
// a platform's cloud save: load it first, then hand it to save
const data = await portal.loadData();
me.save.setStorage(me.save.createCloudStorage({
data,
write: (items) => portal.saveData(JSON.stringify(items)),
}));
// the value in the cloud save, or 0 the first time
me.save.add({ hiscore : 0 });
The shape of the save namespace.
Declared rather than left as a bare index signature: typed as
Record<string, unknown>every member was swallowed by the index, sosave.addcame out asunknownand could not be CALLED at all understrict— the namespace's own documented example did not typecheck — while every registered key read back asunknownand needed a cast to compare or assign.The index signature stays, so anything registered elsewhere is still reachable; declared members simply take precedence over it.