產生程式碼
透過集合功能整理內容
你可以依據偏好儲存及分類內容。
程式碼產生是指將工作區中的區塊轉換為可執行的程式碼字串的程序。
程式碼產生功能非常重要,因為它可讓區塊實際執行操作,例如評估算術運算式、在迷宮中移動角色,或設定網路商店!
Blockly 不會直接「執行」區塊。而是產生程式碼字串,然後執行這些字串。
程式碼產生器
如要產生程式碼,請使用程式碼產生器例項。
下列程式碼片段說明如何為工作區中的區塊產生 JavaScript 程式碼:
// javascriptGenerator is a code generator that makes JavaScript strings.
import {javascriptGenerator} from 'blockly/javascript';
const code = javascriptGenerator.workspaceToCode(myWorkspace);
如要進一步瞭解 Blockly 提供的不同程式碼產生器,以及如何存取這些產生器,請參閱「語言程式碼產生器」。
區塊程式碼產生器
每個區塊都有相關聯的區塊程式碼產生器,可定義產生的程式碼。您必須為每種要產生的語言定義區塊程式碼產生器。
以下程式碼片段會定義「前進」區塊的 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`;
}
如要進一步瞭解如何定義區塊程式碼產生器,請參閱「區塊程式碼產生器」。
執行
產生程式碼後,您需要瞭解如何執行程式碼。決定如何執行這項操作的做法非常特定於應用程式,且超出 Blockly 的範圍。
如要進一步瞭解執行程式碼的方式,請參閱「產生及執行程式碼」。
除非另有註明,否則本頁面中的內容是採用創用 CC 姓名標示 4.0 授權,程式碼範例則為阿帕契 2.0 授權。詳情請參閱《Google Developers 網站政策》。Java 是 Oracle 和/或其關聯企業的註冊商標。
上次更新時間:2025-04-14 (世界標準時間)。
[[["容易理解","easyToUnderstand","thumb-up"],["確實解決了我的問題","solvedMyProblem","thumb-up"],["其他","otherUp","thumb-up"]],[["缺少我需要的資訊","missingTheInformationINeed","thumb-down"],["過於複雜/步驟過多","tooComplicatedTooManySteps","thumb-down"],["過時","outOfDate","thumb-down"],["翻譯問題","translationIssue","thumb-down"],["示例/程式碼問題","samplesCodeIssue","thumb-down"],["其他","otherDown","thumb-down"]],["上次更新時間:2025-04-14 (世界標準時間)。"],[[["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"]]