Get value type in code generator

85 views
Skip to first unread message

Bart Butenaers

unread,
Jul 19, 2021, 4:38:22 PM7/19/21
to Blockly
Hi everybody,

My node allows for input a String, Number or Buffer:

Blockly.Blocks['buffer_set_index'] = {
    init: function () {
        this.jsonInit({
            "type": "buffer_set_index",
            "message0": "%1",
            "args0": [
                {
                    "type": "input_value",
                    "name": "VALUE",
                    "check": ["Number", "String", "Buffer"]
                }
            ],
            "inputsInline": true,
            "previousStatement": null,
            "nextStatement": null
        });
    }
};

In my code generator, I would like to know to which data type my input is connected.
For example in this case it is connected to a Number:

simple_block.png
How can I get the data type in my code generator, to generate code based on the data type:

Blockly.JavaScript['buffer_set_index'] = function(block) {
    const value = Blockly.JavaScript.valueToCode(block, 'VALUE', Blockly.JavaScript.ORDER_ATOMIC);

   dataType = ?????????????????????????????????

   switch (dataType) {
       case "Number":
            code = ...
            break;
        case "String":
             code = ...
             break;
         case "Buffer":
              code = ...
              break;
     }

  return code;
}

Could I use the following info to implement it perhaps:

check_type.png

Thanks!!
Bart
};

Aaron Dodson

unread,
Jul 21, 2021, 7:17:34 PM7/21/21
to Blockly
I think your idea will work, at least in the simple case. Depending on the values and your exact application, it might also work to examine the value you get back from valueToCode() and see if it e.g. parses as a number; OTOH if you're wanting to enforce a type system based on the connected blocks that would of course break down if something entered "5" in a text block.

Bart Butenaers

unread,
Jul 22, 2021, 4:45:45 PM7/22/21
to Blockly
Hi Aaron,
Thanks for sharing your thoughts with me!
The string "5" is indeed an edge case I will need to look at.  Good catch!
Kind regards,
Bart
Reply all
Reply to author
Forward
0 new messages