程式碼生成
產生程式碼是將工作區區塊轉換成
程式碼字串。
程式碼生成極為重要,因為這樣可讓區塊
實際「操作」的方法,例如評估算術運算式、移動字元
或是架設線上商店!
Blockly 不「執行」直接封鎖相反地,您可以產生程式碼字串
然後加以執行
程式碼產生器
如要產生程式碼,請使用程式碼產生器例項。
這個程式碼片段說明如何產生 JavaScript 程式碼,以用於
工作區:
// javascriptGenerator is a code generator that makes JavaScript strings.
import {javascriptGenerator} from 'blockly/javascript';
const code = javascriptGenerator.workspaceToCode(myWorkspace);
進一步瞭解 Blockly 提供的不同程式碼產生器
以及使用方式,請參閱「程式碼產生器總覽」。
區塊程式碼產生器
每個區塊都有相關聯的區塊程式碼產生器,可定義要使用的程式碼
產生的結果。必須為每個語言定義區塊程式碼產生器
想要產生的報表
這段程式碼定義了執行「move」動作的 JavaScript 區塊程式碼產生器
轉寄」區塊:
javascriptGenerator.forBlock['my_custom_block'] = function(block, generator) {
const steps = block.getFieldValue('FIELD_NAME');
// moveForward is a function you would have to define yourself and provide
// within your execution context.
return `moveForward(${steps});\n`;
}
如要進一步瞭解如何定義區塊程式碼產生器,請參閱
區塊程式碼產生器。
執行
產生程式碼後,您需要瞭解執行方式。
決定執行方式的方法會因應用程式而異,而且不在範圍之內
方塊
如要進一步瞭解執行程式碼的方式,請參閱
程式碼執行。
除非另有註明,否則本頁面中的內容是採用創用 CC 姓名標示 4.0 授權,程式碼範例則為阿帕契 2.0 授權。詳情請參閱《Google Developers 網站政策》。Java 是 Oracle 和/或其關聯企業的註冊商標。
上次更新時間:2024-08-22 (世界標準時間)。
[null,null,["上次更新時間:2024-08-22 (世界標準時間)。"],[[["Code generation transforms visual blocks into executable code strings, enabling actions like calculations and character movements within applications."],["Blockly utilizes code generators to produce code in various languages like JavaScript, requiring separate generators for each target language."],["Every block possesses a block-code generator that dictates the specific code it produces for a given language, customizable to your application's needs."],["While Blockly handles code generation, executing the generated code is application-specific and necessitates your own implementation based on the environment."]]],["Code generation converts blocks into executable code strings. Blockly utilizes code generator instances, like `javascriptGenerator`, to transform a workspace's blocks into code. Each block requires a block-code generator, defining its code output, demonstrated in the example with a \"move forward\" block. After code generation, the code must be executed, but this execution process is application-specific and not part of Blockly's core functionality.\n"]]