Hello! I'm new to Blockly and am a beginner programmer. I'm currently trying to edit the value of a variable block within the Javascript generator.
BLOCK DEFINITION
const key_assignment = {
init: function() {
this.appendDummyInput()
.appendField("private key var")
.appendField(new Blockly.FieldVariable("prvKey"), "PRV");
this.appendDummyInput()
.appendField("public key var")
.appendField(new Blockly.FieldVariable("pubKey"), "PUB");
this.setPreviousStatement(true, null);
this.setNextStatement(true, null);
this.setOutput(true, "String");
this.setTooltip('Assigns generated RSA keys to private and public key variables');
this.setHelpUrl('');
this.setColour(225);
}
};
Blockly.common.defineBlocks({list_to_vars : list_to_vars });
JAVASCRIPT GENERATOR
javascript.javascriptGenerator.forBlock['key_assignment'] = function(block) {
const varPrv = Blockly.JavaScript.nameDB_.getName(block.getFieldValue('PRV'), Blockly.Variables.NAME_TYPE);
const varPub = Blockly.JavaScript.nameDB_.getName(block.getFieldValue('PUB'), Blockly.Variables.NAME_TYPE);
const code = `
rsaKeypair = KEYUTIL.generateKeypair("RSA", 1024);
${varPrv} = KEYUTIL.getPEM(rsaKeypair.prvKeyObj, "PKCS8PRV");
${varPub} = KEYUTIL.getPEM(rsaKeypair.pubKeyObj);
`;
return [code, Blockly.JavaScript.ORDER_FUNCTION_CALL];
};
The function generates a pair of RSA keys. Then, it's supposed to assign the private and public keys to their respective variable blocks in the global Blockly space (these variable blocks are named prvKey and pubKey).
However, after running the code, it simply prints the contents of the private and public keys separately; then, when I try to print the contents of prvKey and pubKey variables, it returns "undefined."
Thus, it seems their values were never actually set, but I thought the lines with ${varPrv} and ${varPub} were updating the values of the variable blocks?
Is it even possible to update the value of a Blockly variable in the generator code, or am I just going about it the wrong way?
Thank you in advance!
(Not sure if it's relevant, but here are my injection and execution blocks.)
INJECTION
window.addEventListener('load', () => {
window.workspace = Blockly.inject('blocklyDiv', {
toolbox: document.getElementById('toolbox'),
scrollbars: true
});
});
EXECUTION
function runCode() {
try {
const code = Blockly.JavaScript.workspaceToCode(window.workspace);
const result = eval(code);
document.getElementById('output').textContent = "Result:\n" + result;
} catch (e) {
document.getElementById('output').textContent = "Error:\n" + e;
}
}