diff --git a/docs/local-storage.md b/docs/local-storage.md index 0151ef86a2..b2cef4579f 100644 --- a/docs/local-storage.md +++ b/docs/local-storage.md @@ -44,6 +44,20 @@ Or delete everything stored in the namespace: delete storage :: #0FBD8C ``` +These next blocks are used to inspect and iterate through all namespace items. + +```scratch +(number of keys in storage :: #0FBD8C) +``` + +This block reports the total number of stored variables. + +```scratch +(key # [1] in storage :: #0FBD8C) +``` + +This block reports the name of a key at a specific index position. + ## Performance The local storage extension is inevitably slower than regular variables. diff --git a/extensions/local-storage.js b/extensions/local-storage.js index 85e02b635e..49e1f822c9 100644 --- a/extensions/local-storage.js +++ b/extensions/local-storage.js @@ -204,6 +204,25 @@ blockType: Scratch.BlockType.COMMAND, text: Scratch.translate("delete storage"), }, + "---", + { + opcode: "keyCount", + blockType: Scratch.BlockType.REPORTER, + text: Scratch.translate("number of keys in storage"), + disableMonitor: true, + }, + { + opcode: "itemOfKey", + blockType: Scratch.BlockType.REPORTER, + text: Scratch.translate("key # [NUM] in storage"), + arguments: { + NUM: { + type: Scratch.ArgumentType.NUMBER, + defaultValue: 1, + }, + }, + }, + "---", { opcode: "whenChanged", blockType: Scratch.BlockType.EVENT, @@ -258,6 +277,14 @@ saveToLocalStorage(); } + getAll() { + if (!validNamespace()) { + return ""; + } + + return JSON.stringify(Object.keys(namespaceValues)); + } + removeAll() { if (!validNamespace()) { return ""; @@ -265,6 +292,23 @@ namespaceValues = Object.create(null); saveToLocalStorage(); } + + keyCount() { + if (!validNamespace()) { + return 0; + } + + return Object.keys(namespaceValues).length; + } + + itemOfKey(args) { + if (!validNamespace()) { + return ""; + } + + const keys = Object.keys(namespaceValues); + return keys[Scratch.Cast.toNumber(args.NUM) - 1] ?? ""; + } } Scratch.extensions.register(new LocalStorage());