Unusual JavaScript for loop with xml in Blockly

I'm working on a project with Google's Blockly, but parts of the documentation are incomprehensible. Can someone help me understand the end condition of the following for loop (xml = allXml[i])?

var allXml = Blockly.Xml.workspaceToDom(workspace);
var allCode = [];
for (var i = 0, xml; xml = allXml[i]; i++) {
  var headless = new Blockly.Workspace();
  Blockly.Xml.domToWorkspace(headless, xml);
  allCode.push(Blockly.JavaScript.workspaceToCode(headless));
  headless.dispose();
}

I imagine the loop will exit when allXml[i] is undefined, but how can you iterate through an XML object like this? It seems to always be returning undefined and skipping the loop entirely.

Thanks for you help

Definitions for most of the function can be found at https://code.google.com/p/blockly/source/browse/trunk/core/xml.js?r=1614

And the doc page I pulled this from is https://developers.google.com/blockly/custom-blocks/code-structure?hl=en

Answers:

Answer

I could not find this code in the repo on github, so I guess it is a bit older example in the docs.

But if you will have a look at the Blockly.Xml.workspaceToDom() function's implementation, you will see a very similar thing there.

  var blocks = workspace.getTopBlocks(true);
  for (var i = 0, block; block = blocks[i]; i++) {
    var element = Blockly.Xml.blockToDom_(block);
    //...
    xml.appendChild(element);
  }

The idea here is to iterate over all branches of code. The top block has no top connection (it starts a new branch). The getTopBlocks() returns an array {!Array.<!Blockly.Block>}.

Considering that the documentation is showing it in a section about parallel execution, I think it will be related to the fact, that you can have more unconnected branches of code... and the exact implementation just changed over time.

Answer

As per the code, return type of Blockly.Xml.workspaceToDom(workspace) is {!Element}.

It basically returns a DOM node created using goog.dom.createDom('xml');. And for each top level block it is appending a DOM node to it.

So basically the code snippet in question is looping through all the DOM nodes corresponding to the top level blocks.

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.