> ## Documentation Index
> Fetch the complete documentation index at: https://docs.spurdoverse.app/llms.txt
> Use this file to discover all available pages before exploring further.

# localStorage

> Persistent per-script key-value storage that keeps value types.

The browser's `localStorage`, persistent across script reloads and game restarts. Global, no import.

<Note>
  Storage is per script **folder**, not `manifest.name`. Scripts never see each other's keys.
</Note>

Unlike the browser, values aren't stringified: you get back the type you stored (numbers, booleans,
objects, arrays, `Map`, `Set`, `Date`, typed arrays, `BigInt`). Class instances come back as plain
objects. Functions and native objects (`Vector`, `Pointer`, …) throw a `DataCloneError`.

***

## Methods

### getItem

<br />

```ts theme={null}
localStorage.getItem<T = any>(key: string): T | null
```

A copy of the stored value, or `null` when the key doesn't exist.

```ts theme={null}
const runs = localStorage.getItem<number>("runs") ?? 0;
```

### setItem

<br />

```ts theme={null}
localStorage.setItem(key: string, value: any): void
```

Stores `value` under `key`. `undefined` removes the key, `null` is stored as a value.

```ts theme={null}
localStorage.setItem("runs", runs + 1);
localStorage.setItem("seen", new Set([1, 2, 3]));
localStorage.setItem("runs", undefined);   // removed
```

### Others

| Member | |
| :- | :- |
| `removeItem(key: string): void` | deletes the key |
| `clear(): void` | deletes every key of this script |
| `key(index: number): string \| null` | the key at `index`, `null` when out of range |
| `length: number` | number of keys |

Keys must be strings; anything else throws `TypeError`.

***

## Property access

Keys work as properties too.

```ts theme={null}
localStorage.config = { fov: 90 };
localStorage.config.fov;          // 90
delete localStorage.config;
Object.keys(localStorage);        // every key
localStorage.fov = undefined;     // removes "fov"
```

Keys named like a method, `length` or `toString` need `getItem` / `setItem`.

***

## Example

Remember the last few maps played.

```ts theme={null}
import game from "@native/game";

let lastMap: string | null = null;

on("tick", () => {
    const map = game.shortMapName;
    if (!map || map === lastMap) return;
    lastMap = map;

    const recent = localStorage.getItem<string[]>("recentMaps") ?? [];
    const next = [map, ...recent.filter((m) => m !== map)].slice(0, 5);
    localStorage.setItem("recentMaps", next);
    console.log("recent maps:", next.join(", "));
});
```
