2

How can I make a block that compiles to wrap all blocks that follow it?

Here is an example of the block I want to make:

enter image description here

I want to write generators that create the output:

console.log('1');
console.log('2');
(function () {
  console.log('3');
  console.log('4');
}());

I have thought of two possible solutions:

My idea 1

The pseudo-C-block generator should do what a normal C-block generator does.

  1. Get the transpilation of all following blocks.
  2. Prevent Blockly from automatically transpiling the following blocks itself.

I have already looked at doing 1 using block.nextConnection.targetBlock() and Blockly.JavaScript.blockToCode. It's inconvenient to loop like that, and I also haven't figured out how to solve the second point.

The second point is because I don't want output like

console.log('1');
console.log('2');
(function () {
  console.log('3');
  console.log('4');
}());
console.log('3');
console.log('4');

My idea 2

Create a custom style for the pseudo-C-block. It really does have a input_statement argument, but the input_statement is invisible to the user and instead any blocks attached to the bottom of the psuedo-C-block are actually being attached into that input_statement

Unfortunately I have no idea how to accomplish this.


Please could someone point me in the right directions?

theonlygusti
  • 11,032
  • 11
  • 64
  • 119
  • Gotcha. Is there a reason not to wrap the entire generated JS output in an IIFE? I guess you want to expose some lines of code to the global scope and some not? – ggorlen Apr 11 '21 at 14:31
  • @ggorlen I have lots of cases where this is a useful abstraction. One example usecase could be adding a "wait" block, you'd have to wrap the following statements inside of a `setTimeout(function () { ... })` construct – theonlygusti Apr 11 '21 at 14:33
  • Interesting. So you don't necessarily care about an IIFE, then. I'm just trying to get to the bottom of what you hope to accomplish and avoid an [XY problem](https://meta.stackexchange.com/questions/66377/what-is-the-xy-problem). For example, you could implement `wait` with the typical `await new Promise(res => setTimeout(res, delay))` pattern, which doesn't require closure management other than making sure you're running in an `async` function. it seems you're trying to avoid "callback hell" in blockly by flattening out the nesting... – ggorlen Apr 11 '21 at 14:37
  • @ggorlen I am generating code to run on Bukkit minecraft servers. So I'd use the Bukkit scheduler instead of `setTimeout`, and in this environment everything has to run on the main thread so using JS asynchronicity is unfortunately out the window (I believe async IIFE doesn't run on the main thread?) – theonlygusti Apr 11 '21 at 14:51

0 Answers0