How to get value of variable in code generator

815 views
Skip to first unread message

Dennis Baldwin

unread,
Mar 4, 2016, 4:58:03 PM3/4/16
to Blockly
Hi,

First off we are really enjoying Blockly. Kudos to the dev team for all the hard work!

I have a question that I couldn't find an answer to in the documentation or this group. We are trying to get the value of a variable in our custom block's code generator. It looks something like this:

Blockly.JavaScript['move'] = function(block) {
  var distance = Blockly.JavaScript.valueToCode(block, 'distance', Blockly.JavaScript.ORDER_NONE);
  return "move," + distance;
};

In the cases where we have a number input it returns just fine like this:

move,30

But if we have a variable, let's say "x", then it returns this:

move,x

The image below shows an example of both cases above where a hardcoded number is applied and then with a variable:


Any ideas how we go about evaluating the value of x in our generator? Or is there another way to go about this? We want users to be able to specify a numeric input directly or use a variable.


Thank you.


Avi

unread,
Mar 4, 2016, 6:07:17 PM3/4/16
to Blockly
Dennis,

You are confusing code generation phase and code run phase.

During code generation, the two blocks, 'set x' and 'move x' are completely independent. Blockly just looks at the blocks one by one, and generates code (strings) for them by calling their individual Blockly.Javascript [xxx] function. You will not be able to get value 30 during code generation, since Blockly does not interpret the code, it simply generates strings and combines them as whole.

The generated code is then given to the runtime engine, through eval etc (this is what happens when you click Run in Blockly demos)
It's during run time, that things start coming together ..
The first block generates var x; x = 30;  after this line is run , x will be 30
the next block generates move x (which will be interpreted as move,30)

In short whatever is interpreting(running) your "move,30" should also be able to interpret var x; x=30; move,x;
also see .. last 3 replies on
https://groups.google.com/forum/#!topic/blockly/T4Clh7HvCSg/discussion

hope this helps

Regards
Avi

Dennis Baldwin

unread,
Mar 4, 2016, 6:54:56 PM3/4/16
to blo...@googlegroups.com
Thank you for that clarification, Avi. We are actually passing this data to Objective C so we'll need to come up with something to "interpret" this code. 

--
You received this message because you are subscribed to a topic in the Google Groups "Blockly" group.
To unsubscribe from this topic, visit https://groups.google.com/d/topic/blockly/H1P4N2YLdnQ/unsubscribe.
To unsubscribe from this group and all its topics, send an email to blockly+u...@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Reply all
Reply to author
Forward
0 new messages