Hello Blockly team
Finally, with tenacity, I managed to generate some code before an assignment was generated.
For this, there are 3 updates :
1) Add the declaration in core/block.ts:
prelude_code: string = '';
2) In generators/<language>/variables.ts
Replace the "variables_set" function by:
export function variables_set(block: Block, generator: BasicGenerator) {
// Setter variable.
block.prelude_code = '';
const argument0 = generator.valueToCode(block, 'VALUE', Order.ASSIGNMENT) || '0';
const varName = generator.getVariableName(block.getFieldValue('VAR'));
return block.prelude_code + varName + ' = ' + argument0 + '\n';}
3) In the function that wants to generate code BEFORE the assignment do :
(for example in math.ramdom :)
let code = '';
let prelude_code = '';
let block_Parent = block.getParent();
let block_Parent_type = (block_Parent == null) ? 'Null': block_Parent.type;
// This prelude_code must be generated ONLY if block_Parent_type == 'variables_set'
prelude_code += "''***Assign Parameters and Call the Function:\n";
prelude_code += 'a = ' + argument0 + '\n' +
'b = ' + argument1 + '\n' +
functionName + "() '(" + argument0 + ', ' + argument1 + ")'\n" +
"''***End Function Call\n";
if (block_Parent_type == 'variables_set')
{
if (block_Parent != null)
{block_Parent.prelude_code += prelude_code;
code = functionName + "_Return_Value";
}
else
{code = '***Generation Error! block.parent is null\n';}
}
else // (block_Parent_type != 'variables_set')
{
code = functionName + "_Return_Value\n" + '***Generation Error: block_Parent_type=' + block_Parent_type + '\n' + prelude_code;
}
==> And that’s it!
Rather than constraining this generation BEFORE an assignment, it would have been better to search for the start of the main instruction.
Thus, we would no longer be limited to:
block_Parent_type == 'variables_set'
but rather to:
block_Parent_... Parent_type == <main instruction type>
But I didn't go that far !
If you could help me, it would expand my constraint.
Thank you for your help !
Daniel