extensions: Create Variable Blocks

I have a code for an extension that will create or delete variables in the editor:

 class VariableExtension {
  constructor(runtime) {
    this.runtime = runtime;
  }

  getInfo() {
    return {
      id: 'variableExtension',
      name: 'Variable Extension',
      blocks: [
        {
          opcode: 'createVariable',
          blockType: 'command',
          text: 'create variable [variableName]',
          arguments: {
            variableName: {
              type: 'string',
              defaultValue: 'myVariable'
            }
          }
        },
        {
          opcode: 'renameVariable',
          blockType: 'command',
          text: 'rename variable [variableName] to [newName]',
          arguments: {
            variableName: {
              type: 'string',
              defaultValue: 'myVariable'
            },
            newName: {
              type: 'string',
              defaultValue: 'newVariableName'
            }
          }
        },
        {
          opcode: 'deleteVariable',
          blockType: 'command',
          text: 'delete variable [variableName]',
          arguments: {
            variableName: {
              type: 'string',
              defaultValue: 'myVariable'
            }
          }
        }
      ]
    };
  }

  createVariable(args, util) {
    const variableName = args.variableName;
    Blockly.getMainWorkspace().createVariable(variableName);
  }

  renameVariable(args, util) {
    const variableName = args.variableName;
    const newName = args.newName;
    const variable = Blockly.getMainWorkspace().getVariable(variableName);
    if (variable) {
      Blockly.getMainWorkspace().renameVariableById(variable.getId(), newName);
    }
  }

  deleteVariable(args, util) {
    const variableName = args.variableName;
    const variable = Blockly.getMainWorkspace().getVariable(variableName);
    if (variable) {
      Blockly.getMainWorkspace().deleteVariableById(variable.getId());
    }
  }
}

Scratch.extensions.register(new VariableExtension());

About this issue

  • Original URL
  • State: open
  • Created 9 months ago
  • Reactions: 5
  • Comments: 16 (11 by maintainers)

Most upvoted comments

how do you read them though, also dynamically

Yo actually, this seems really useful!