math_single block, text_length block throw errors

64 views
Skip to first unread message

Max Stephen Russell

unread,
Feb 14, 2025, 6:47:40 PM2/14/25
to Blockly
When I move some blocks such as math_single and text_length from the toolbox, I get errors for the current displayed value, like the following displayed for the math_single block. May I ask for a suggestion or explanation? Thank you! -Steve
 
Uncaught runtime errors:
ERROR
sqrt is not defined
ReferenceError: sqrt is not defined
    at eval (eval at runCode (webpack-internal:///./src/index.js), <anonymous>:1:1)
    at runCode (webpack-internal:///./src/index.js:52:3)
    at eval (webpack-internal:///./src/index.js:79:3)
    at WorkspaceSvg$$module$build$src$core$workspace_svg.fireChangeListener (webpack-internal:///./node_modules/blockly/blockly_compressed.js:1158:456)
    at fireNow$$module$build$src$core$events$utils (webpack-internal:///./node_modules/blockly/blockly_compressed.js:75:340)



Mark Friedman

unread,
Feb 14, 2025, 7:44:35 PM2/14/25
to blo...@googlegroups.com
Have you changed the code generator for those blocks?.  Also, could you show us the code which causes those errors?

-Mark


--
You received this message because you are subscribed to the Google Groups "Blockly" group.
To unsubscribe from this group and stop receiving emails from it, send an email to blockly+u...@googlegroups.com.
To view this discussion visit https://groups.google.com/d/msgid/blockly/4e2eed89-d16b-4753-9d4b-54210f85f0afn%40googlegroups.com.

Max Stephen Russell

unread,
Feb 14, 2025, 8:48:17 PM2/14/25
to Blockly
Yes, I first experimented with the original JavaScript generator, then I switched to PHP. I will gladly send my code in a separate message, but first -- You may remember that I took the advice from some of you to use the starter app and build on it, which is what I am doing with great care. Remembering that there had been occasional errors before I began testing custom blocks and switching to PHP, tonight I installed the starter app again, elsewhere of course, and will now report the following results:

A few uncaught runtime errors in a brand new installation of the starter app via npx @blockly/create-package app hello-world:

lists_getSublist block:

Cannot read properties of undefined (reading 'slice')
TypeError: Cannot read properties of undefined (reading 'slice')
    at eval (eval at runCode (webpack-internal:///./src/index.js), <anonymous>:4:6)
    at runCode (webpack-internal:///./src/index.js:42:3)
------
procedures_ifreturn block:

Illegal return statement
SyntaxError: Illegal return statement
    at runCode (webpack-internal:///./src/index.js:42:8)
    at eval (webpack-internal:///./src/index.js:69:3)
    . . . 
------
controls_flow_statements block:

Illegal break statement
SyntaxError: Illegal break statement
    at runCode (webpack-internal:///./src/index.js:42:8)
    at eval (webpack-internal:///./src/index.js:69:3)
    . . .
------
text_indexOf block:

ERROR
Cannot read properties of undefined (reading 'indexOf')
TypeError: Cannot read properties of undefined (reading 'indexOf')
    at eval (eval at runCode (webpack-internal:///./src/index.js), <anonymous>:13:6)
    at runCode (webpack-internal:///./src/index.js:42:3)
    at eval (webpack-internal:///./src/index.js:69:3)

    at WorkspaceSvg$$module$build$src$core$workspace_svg.fireChangeListener (webpack-internal:///./node_modules/blockly/blockly_compressed.js:1158:456)
    at fireNow$$module$build$src$core$events$utils (webpack-internal:///./node_modules/blockly/blockly_compressed.js:75:340)

Thank you.

-Steve

Max Stephen Russell

unread,
Feb 14, 2025, 8:57:02 PM2/14/25
to Blockly
index.js
/**
 * @license
 * Copyright 2023 Google LLC
 * SPDX-License-Identifier: Apache-2.0
 */

import * as Blockly from 'blockly';
import {blocks} from './blocks/theblocks';
///import {forBlock} from './generators/javascript';
///import {javascriptGenerator} from 'blockly/javascript';
import {forBlock} from './generators/php';
import {phpGenerator} from 'blockly/php';
import {save, load} from './serialization';
import {toolbox} from './toolbox';
import './custom_category';
import './toolbox_label';
import './toolbox_style.css';
import './index.css';

// Register the blocks and generator with Blockly
Blockly.common.defineBlocks(blocks);
///Object.assign(javascriptGenerator.forBlock, forBlock);
Object.assign(phpGenerator.forBlock, forBlock);

// Set up UI elements and inject Blockly
const codeDiv = document.getElementById('generatedCode').firstChild;
const outputDiv = document.getElementById('output');
const blocklyDiv = document.getElementById('blocklyDiv');
const ws = Blockly.inject(blocklyDiv, {toolbox});

// This function resets the code and output divs, shows the
// generated code from the workspace, and evals the code.
// In a real application, you probably shouldn't use `eval`.
const runCode = () => {
  ///const code = javascriptGenerator.workspaceToCode(ws);
  const code = phpGenerator.workspaceToCode(ws);
  codeDiv.innerText = code;

  outputDiv.innerHTML = '';

  eval(code);
};

// Load the initial state from storage and run the code.
load(ws);
runCode();

// Every time the workspace changes state, save the changes to storage.
ws.addChangeListener((e) => {
  // UI events are things like scrolling, zooming, etc.
  // No need to save after one of these.
  if (e.isUiEvent) return;
  save(ws);
});

// Whenever the workspace changes meaningfully, run the code again.
ws.addChangeListener((e) => {
  // Don't run the code when the workspace finishes loading; we're
  // already running it once when the application starts.
  // Don't run the code during drags; we might have invalid state.
  if (
    e.isUiEvent ||
    e.type == Blockly.Events.FINISHED_LOADING ||
    ws.isDragging()
  ) {
    return;
  }
  runCode();
});



php.js
import {phpGenerator, Order} from 'blockly/php';

// Export all the code generators for our custom blocks,
// but don't register them with Blockly yet.
// This file has no side effects!
export const forBlock = Object.create(null);

forBlock['add_text'] = function (block, generator) {
  const text = generator.valueToCode(block, 'TEXT', Order.NONE) || "''";
  const addText = generator.provideFunction_(
    'addText',
    `function ${generator.FUNCTION_NAME_PLACEHOLDER_}(text) {

  // Add text to the output area.
  const outputDiv = document.getElementById('output');
  const textEl = document.createElement('p');
  textEl.innerText = text;
  outputDiv.appendChild(textEl);
}`,
  );
  // Generate the function call for this block.
  const code = `${addText}(${text});\n`;
  return code;
};
/*
forBlock['setup01'] = function (block, generator) {
    // Collect argument strings.
    const fieldValue = generator.quote_(block.getFieldValue('COUNTRY'));
    const fieldValue2 = generator.quote_(block.getFieldValue('labelBillOrLaw'));
    const fieldValue3 = generator.quote_(block.getFieldValue('labelLawNum'));

    // Generate the function call for this block.
  const code = `${fieldValue} != ${fieldValue2}\n && ${fieldValue2} != ${fieldValue3};\n`;
  return code;
};
/*
forBlock['controls_if_then'] = function (block, generator) {
  // Collect argument strings.
  // Collect inner block code strings.
  const innerCode = generator.statementToCode(block, 'IF0');
  const innerCode2 = generator.statementToCode(block, 'THEN0');
//  const fieldValue = generator.quote_(block.getFieldValue('IF0'));
//  const fieldValue2 = generator.quote_(block.getFieldValue('THEN0'));

  // Generate the function call for this block.
const code = "";//`${innerCode2};\n`;
return code;
};*/

//const code = phpGenerator.workspaceToCode(myWorkspace);
--------

On Friday, February 14, 2025 at 7:44:35 PM UTC-5 mark.f...@gmail.com wrote:

Mark Friedman

unread,
Feb 14, 2025, 9:10:12 PM2/14/25
to blo...@googlegroups.com
You can't use JavaScript's eval() function with generated PHP code. If your want to use PHP you'll have to save that generated code somewhere and import it into your PHP program.

-Mark

Max Stephen Russell

unread,
Feb 14, 2025, 9:20:53 PM2/14/25
to Blockly
I wish I could say I understand what you're telling me, Mark. Do I need to remove eval() and then . . . what? What will I do differently from what I did when I was still in JavaScript?

Thank you. I think this generator business may be my last great hurdle.

Steve

Max Stephen Russell

unread,
Feb 14, 2025, 11:14:25 PM2/14/25
to Blockly
Thank you for clearing up my very unpleasant errors, that is, after I switched back to JavaScript. The variety of other block errors I reported from the starter app remain in my app, which began as the starter app.

Mark Friedman

unread,
Feb 15, 2025, 8:19:48 PM2/15/25
to blo...@googlegroups.com
Steve,

  Maybe it would help to take a step back and consider the basic why and how of Blockly.  

  So first, why?  Typically, a developer using Blockly wants to build some sort of web app that enables their users to do some kind of coding. That web app might enable their users to build mobile apps, or control robots or learn CS principles in the context of playing games.  The reason they want to use Blockly in their app is so that their users don't have to code using a textual programming language.  Blockly enables an easier way for their users to code.  

  And the how?  In all the cases mentioned above, they need to run their users' code in the context of some other device or environment: e.g., a mobile device, a robot OS, or a set of graphics commands.  To do so requires (in most cases) running some textual code in that environment.  That code could be in any programming language, depending on that other environment. So, Blockly enables the generation of the textual code from their users' visual blocks-based program.  It's up to the developer of the Blockly-based web app to take that code and integrate it into the environment in which it has to run. It could be something like sending the code to a server, which compiles it as part of a larger program, or it could send it to a device which directly interprets the code.  There's lot of ways to use the code that's generated by Blockly

  The sample app is just a starting point for developing the kind of web apps that I mentioned above.  The use of eval() in the sample app is possibly misleading, in that it assumes: 
  • That you want to run the users' program in the same context as the web app, which is almost never what the developer wants
  • That you want to generate and run only JavaScript code. That might not be the case for that developer's particular environment.  Blockly can generate any programming language your environment requires.
  Further, note that JavaScript's eval() function can only evaluate JavaScript code.  It can't evaluate PHP, Python, Lua, Dart, or other languages that you might build a Blockly code generator for. And even for generated JavaScript code it's rarely safe or effective to use eval()

  If you really want to use PHP as your generated programming language afaik, there is no interpreter for PHP that runs in a browser (i.e. no equivalent to JavaScript's eval() for PHP).

  Unfortunately, the Blockly documentation doesn't give much guidance for exactly how to integrate non-JavaScript generated code (for integrating JavaScript generated code it gives some guidance here).  For now you might still get some help from this group, since many folks here, of course, have implemented web apps using Blockly.  You might start by telling the group what kind of web app you want to build and where you imagine Blockly fits in.

-Mark


Max Stephen Russell

unread,
Feb 15, 2025, 10:58:39 PM2/15/25
to Blockly
Hello Mark, and thank you for the beautiful exposition, which should be pinned for newcomers to read and take encouragement from. Having read most of the guides and worked most of the codelabs, sometimes repeatedly, I try to ask proper Blockly questions. You folks have been generous with your responses to my many questions. 😎 As of today, I almost hesitate to say, I think the wind is at my back. You and Ron have offered some invaluable remarks and explanations lately. I really, really appreciate the assistance! It’s kind of funny — you wouldn’t know I have a pretty big bag of tricks. As for the potentially misleading assumption of eval()  which you mention:
  • That you want to run the users' program in the same context as the web app, which is almost never what the developer wants
That is exactly what I am building. 😎

Steve

Mark Friedman

unread,
Feb 16, 2025, 1:01:44 PM2/16/25
to blo...@googlegroups.com
Thanks for the kind words, Steve.  Please make sure that you reread Blockly's doc on generating and running JavaScript that I linked to (here).  That should help in creating a reasonably safe and performant app.

-Mark


Max Stephen Russell

unread,
Feb 16, 2025, 1:49:33 PM2/16/25
to Blockly
Mark, I will definitely reread that doc, more than once, and already have. When you all go to the trouble of including links, I read them!

"a reasonably safe and performant app" ? I have a zero bug policy, and I will maintain it even in the Wild West of JavaScript, no matter what.  😎 Although I admit it is hard to be quite so confident in a browser. I am very impressed with various features of Blockly, and I intend not to waste my development time but rather to report every glitch I run into and only navigate in what I observe to be the most stable functionality, and cross the finish line with Blockly humming along in perfect working order.

Steve

Reply all
Reply to author
Forward
0 new messages