Get value from variable

4,403 views
Skip to first unread message

Steven Kitzes

unread,
Nov 24, 2015, 6:48:13 PM11/24/15
to Blockly
I am trying to 'set' a variable, then 'get' it to use it in a custom block I've created.  But I'm not getting the value of the variable, I'm getting its name instead.

Here is a picture to clarify:

And here is the code for the 'Display var:' block I made using the Blockly Block Factory:

Blockly.Blocks['var_block'] = {
  init
: function() {
   
this.appendDummyInput()
       
.appendField("Display var: ");
   
this.appendValueInput("MYVAR")
       
.setCheck("Number");
   
this.setInputsInline(true);
   
this.setPreviousStatement(true, null);
   
this.setNextStatement(true, null);
   
this.setColour(290);
 
}
};


Blockly.JavaScript['var_block'] = function(block) {
 
var myval = Blockly.JavaScript.valueToCode(block, 'MYVAR', Blockly.JavaScript.ORDER_ATOMIC);
  console
.log(myval);
};

The console output is:

"item"

How do I get it to return the value 0 (zero)?

Note, for the Blockly.JavaScript ... portion I also tried:

Blockly.JavaScript['var_block'] = function(block) {
 
var myval = block.getFieldValue('MYVAR');
  console
.log(myval);
};

But the result of the console output in this case was:

null

Avi

unread,
Nov 25, 2015, 4:23:16 PM11/25/15
to Blockly
Use Field->variable in Blockly Factory.

This should give you the code

.appendField(new Blockly.FieldVariable("item"), "MYVAR");

The whole block would look like this

Blockly.Blocks['var_block'] = {
  init
: function() {
   
this.appendDummyInput()
       
.appendField("Display var:")

       
.appendField(new Blockly.FieldVariable("item"), "MYVAR");
   
this.setInputsInline(true);
   
this.setPreviousStatement(true);
   
this.setNextStatement(true);
   
this.setTooltip('');
   
this.setHelpUrl('http://www.example.com/');
 
}
};

Blockly.JavaScript['var_block'] = function(block) {
 
var myvar = Blockly.JavaScript.variableDB_.getName(block.getFieldValue('MYVAR'), Blockly.Variables.NAME_TYPE);
  console
.log(myvar);
 
var code = '...';  //Build code here
 
return code;
};

Avi

unread,
Nov 25, 2015, 5:31:04 PM11/25/15
to Blockly
You could build the code like
code = 'console.log(' + myvar + ');\n' ;

Steven Kitzes

unread,
Nov 27, 2015, 2:48:19 PM11/27/15
to Blockly
I'm still dramatically confused... here is code with line numbers:

01  Blockly.Blocks['myblock'] = {
02    init: function() {
03      this.appendDummyInput()
04        .appendField("hello")
05        .appendField(new Blockly.FieldVariable("item"), "MYVAR");
06      this.setInputsInline(true);
07      this.setPreviousStatement(true, null);
08      this.setNextStatement(true, null);
09      this.setColour(20);
10      this.setTooltip('');
11      this.setHelpUrl('http://www.example.com/');
12   
}
13  };
14
15  Blockly.JavaScript['myblock'] = function(block) {
16   
var myvar = Blockly.JavaScript.variableDB_.getName(block.getFieldValue('MYVAR'), Blockly.Variables.NAME_TYPE);
17    alert
(myvar);
18   
var code = 'alert("got something: " + ' + myvar + ');';
19   
return code;
20  };

Here is an image of the blocks:

On line 17, the alert pop-up displays the variable myvar as "item".  But lines 18-19 return code where the variable myvar comes out as expected, "hello world" ... why does myvar have a different value from one line to the next?  How is this working, and how can I use/manipulate myvar if needed before returning it as part of the code variable string?

Avi

unread,
Nov 27, 2015, 4:51:43 PM11/27/15
to Blockly
The value of myvar does not change. it is always equal to 'item' ( or whatever variable value you set on the brown block).
The 'code' is evaluated. When the below code is evaluated (run)

var item;
item
= "hello world';   //This is what the first block will do.
alert("
got something: " + item);   // This is how the generated code by brown block would look

It would alert the text 'got something: hello world'

The function
Blockly.JavaScript['myblock'] = function(block) is used to generate code , which later gets evaluated (like when clicking 'Run Program' in Blockly games)

Steven Kitzes

unread,
Nov 27, 2015, 6:04:13 PM11/27/15
to Blockly
This is the single most helpful thing I've read about Blockly.  Thank you so much for explaining it!  It always seems to obvious once explained.

Riderman Sousa

unread,
Aug 21, 2017, 8:25:43 PM8/21/17
to Blockly
And about another languages?

I my case I'm creating a generator for JSON, so I really need the variable value...

Blockly.JSON.variables_get = function variablesGet() {
const code = Blockly.JSON.valueToCode(this, 'VAR', Blockly.JSON.ORDER_ATOMIC);
return [code, Blockly.JSON.ORDER_ATOMIC];
};

But always is an empty string `""`

I need the actually value because this will generate a JSON.

Han Yang

unread,
Aug 24, 2017, 8:02:50 PM8/24/17
to Blockly, steven...@gmail.com
Hi, I also met this question and could not understand what you have wrote completely. If you could do me a favor, I will really appreciate.

This is my question:
I want to write a custom block looks like below:

I would like to get the value of variable named P_Table, however, it could only get the value of "P_Table". What do I need to do to solve this?

The following is the definition and generator stub:

Blockly.Blocks['bittochar'] = {
  init: function() {
    this.appendDummyInput()
        .appendField("BitToChar");
    this.appendValueInput("input")
        .setCheck("Array")
        .setAlign(Blockly.ALIGN_RIGHT)
        .appendField("input")
        .appendField(new Blockly.FieldVariable("item"), "input");
    this.appendValueInput("Bits")
        .setCheck("Number")
        .setAlign(Blockly.ALIGN_RIGHT)
        .appendField("bits");
    this.setOutput(true, "Array");
    this.setColour(75);
 this.setTooltip("Transfer bit to char array");
 this.setHelpUrl("");
  }
};
Blockly.JavaScript['bittochar'] = function(block) {
    var variable_input = Blockly.JavaScript.variableDB_.getName(block.getFieldValue('input'), Blockly.Variables.NAME_TYPE);
    var value_input = Blockly.JavaScript.valueToCode(block, 'input', Blockly.JavaScript.ORDER_ATOMIC);
    console.log(variable_input);
    var value_bits = Blockly.JavaScript.valueToCode(block, 'Bits', Blockly.JavaScript.ORDER_ATOMIC);
    var output_char = [0,0,0,0,0,0,0,0];
    value_input = string2Array(value_input);
    for (j = 0; j <= 7; j++) {
        for (i = 0; i <= 7; i++) {
            output_char[j] = output_char[j] * 2 + parseInt(value_input[i + 8 * j]);
        }
    }
    console.log(output_char);
    return output_char;
};

By the way, the output of this custom block should be an Array, and when I want to print it, the outcome is just the first number of the array. If I want to print out all the array, what should I do?

Thanks very much!

Han

在 2015年11月24日星期二 UTC下午11:48:13,Steven Kitzes写道:

Cory Diers

unread,
Aug 25, 2017, 1:54:55 PM8/25/17
to Blockly
The answer to this question is the same as above. Blockly's goal is to generate code. The output of every block is a string, the code which is intended to be run later. So when you have these blocks:


The generated result (for JavaScript) is:

window.alert(x);

If x is set to "Hello, world!" earlier in the stack, it does not generate:

window.alert("Hello, world!");

That's because Blockly generates code. Variable blocks don't "know" what value is contained in them, they just know which variable name they contain (and now, optionally, the type of that variable). The generator you have there is a bit strange. Take a look at the variables_get generator for Python:

Blockly.Python['variables_get'] = function(block) {
  // Variable getter.
  var code = Blockly.Python.variableDB_.getName(block.getFieldValue('VAR'),
      Blockly.Variables.NAME_TYPE);
  return [code, Blockly.Python.ORDER_ATOMIC];
};

Since the variables_get block is atomic, it shouldn't be calling valueToCode. valueToCode should be called when a block has value inputs. This block should be pulling the value of its field, and returning code. In the case of variables, the name of the variable can be found on the language's variableDB_. However, this will still return the name of the variable, not the value.

So, using variable blocks when generating JSON isn't going to work like you want them to, but I'm not sure they're appropriate. JSON doesn't have a concept of variables, so using a variable block to generate JSON seems out of place to me. You could create a new block type to hold your variables, but I think that will wind up being a pretty serious undertaking. I would suggest not using variable blocks to generate JSON.

Cory Diers

unread,
Aug 25, 2017, 2:01:27 PM8/25/17
to Blockly, steven...@gmail.com
Han,

I think the confusion you're having is similar to Riderman's. The output of your block should be a string - it should be code, not the result of your function. I wrote a response Wednesday to a question that seems to have gotten gobbled up somehow by Google Groups:


Also, in another's words, maybe this will help explain why Blockly is generating strings: https://devschoolblog.wordpress.com/2014/09/24/blockly-versus-scratch-an-apology/amp/
Message has been deleted

isnullxbh

unread,
Feb 21, 2018, 9:25:17 AM2/21/18
to Blockly
Example:

Blockly.Blocks['stop_actions'] = {
    init: function() {
        var actions_descriptors = [
            ['HOLD', 'hold'],
            ['COAST', 'coast']
        ];
        this.appendDummyInput()
            .appendField(new Blockly.FieldDropdown(actions_descriptors), 'action')
            .setAlign(Blockly.ALIGN_RIGHT);
        this.setOutput(true, 'String');
        this.setColour(60);
        this.setTooltip('Select the stop action');
    }
};

Blockly.Blocks['motor'] = {
    init: function() {
        this.appendValueInput('arg_stop_action')
            .appendField('Stop action')
            .setAlign(Blockly.ALIGN_RIGHT);
    },

    onchange: function(e) {
        // !
        this.getInputTargetBlock('arg_stop_action').getFieldValue('action');
    }
};

picklesrus

unread,
Feb 21, 2018, 2:39:23 PM2/21/18
to Blockly
Hi isnullxbh,

I can't figure out the context of this message given that previous messages have been deleted and the thread spans several years. If you have a question, could you please state it again? 

Thanks!
- picklesrus

isnullxbh

unread,
Feb 28, 2018, 4:05:46 AM2/28/18
to Blockly
Hi picklesrus! No, I just wanted to show how may get the variable value (variable - by this I mean another block connected to input value of current block). It's reply for first message in thread.

Thanks for reply!

picklesrus

unread,
Feb 28, 2018, 3:29:56 PM2/28/18
to Blockly
Excellent. I just wanted to make sure I wasn't missing something :)
Thanks!
Reply all
Reply to author
Forward
0 new messages