diff --git a/generators/lua.js b/generators/lua.js index bee88de91..391a0ca87 100644 --- a/generators/lua.js +++ b/generators/lua.js @@ -16,189 +16,204 @@ goog.declareModuleId('Blockly.Lua'); import * as stringUtils from '../core/utils/string.js'; // import type {Block} from '../core/block.js'; import {CodeGenerator} from '../core/generator.js'; -import {inputTypes} from '../core/inputs/input_types.js'; import {Names} from '../core/names.js'; // import type {Workspace} from '../core/workspace.js'; +import {inputTypes} from '../core/inputs/input_types.js'; -/** - * Lua code generator. - * @type {!CodeGenerator} - */ -const Lua = new CodeGenerator('Lua'); - -/** - * List of illegal variable names. - * This is not intended to be a security feature. Blockly is 100% client-side, - * so bypassing this list is trivial. This is intended to prevent users from - * accidentally clobbering a built-in object or function. - */ -Lua.addReservedWords( - // Special character - '_,' + - // From theoriginalbit's script: - // https://github.com/espertus/blockly-lua/issues/6 - '__inext,assert,bit,colors,colours,coroutine,disk,dofile,error,fs,' + - 'fetfenv,getmetatable,gps,help,io,ipairs,keys,loadfile,loadstring,math,' + - 'native,next,os,paintutils,pairs,parallel,pcall,peripheral,print,' + - 'printError,rawequal,rawget,rawset,read,rednet,redstone,rs,select,' + - 'setfenv,setmetatable,sleep,string,table,term,textutils,tonumber,' + - 'tostring,turtle,type,unpack,vector,write,xpcall,_VERSION,__indext,' + - // Not included in the script, probably because it wasn't enabled: - 'HTTP,' + - // Keywords (http://www.lua.org/pil/1.3.html). - 'and,break,do,else,elseif,end,false,for,function,if,in,local,nil,not,or,' + - 'repeat,return,then,true,until,while,' + - // Metamethods (http://www.lua.org/manual/5.2/manual.html). - 'add,sub,mul,div,mod,pow,unm,concat,len,eq,lt,le,index,newindex,call,' + - // Basic functions (http://www.lua.org/manual/5.2/manual.html, section 6.1). - 'assert,collectgarbage,dofile,error,_G,getmetatable,inpairs,load,' + - 'loadfile,next,pairs,pcall,print,rawequal,rawget,rawlen,rawset,select,' + - 'setmetatable,tonumber,tostring,type,_VERSION,xpcall,' + - // Modules (http://www.lua.org/manual/5.2/manual.html, section 6.3). - 'require,package,string,table,math,bit32,io,file,os,debug'); - /** * Order of operation ENUMs. * http://www.lua.org/manual/5.3/manual.html#3.4.8 + * @enum {number} */ -Lua.ORDER_ATOMIC = 0; // literals -// The next level was not explicit in documentation and inferred by Ellen. -Lua.ORDER_HIGH = 1; // Function calls, tables[] -Lua.ORDER_EXPONENTIATION = 2; // ^ -Lua.ORDER_UNARY = 3; // not # - ~ -Lua.ORDER_MULTIPLICATIVE = 4; // * / % -Lua.ORDER_ADDITIVE = 5; // + - -Lua.ORDER_CONCATENATION = 6; // .. -Lua.ORDER_RELATIONAL = 7; // < > <= >= ~= == -Lua.ORDER_AND = 8; // and -Lua.ORDER_OR = 9; // or -Lua.ORDER_NONE = 99; +export const Order = { + ATOMIC: 0, // literals + // The next level was not explicit in documentation and inferred by Ellen. + HIGH: 1, // Function calls, tables[] + EXPONENTIATION: 2, // ^ + UNARY: 3, // not # - ~ + MULTIPLICATIVE: 4, // * / % + ADDITIVE: 5, // + - + CONCATENATION: 6, // .. + RELATIONAL: 7, // < > <= >= ~= == + AND: 8, // and + OR: 9, // or + NONE: 99, +}; /** + * Lua code generator class. + * * Note: Lua is not supporting zero-indexing since the language itself is * one-indexed, so the generator does not repoct the oneBasedIndex configuration * option used for lists and text. */ +class LuaGenerator extends CodeGenerator { + constructor(name) { + super(name ?? 'Lua'); + this.isInitialized = false; -/** - * Whether the init method has been called. - * @type {?boolean} - */ -Lua.isInitialized = false; - -/** - * Initialise the database of variable names. - * @param {!Workspace} workspace Workspace to generate code from. - */ -Lua.init = function(workspace) { - // Call Blockly.CodeGenerator's init. - Object.getPrototypeOf(this).init.call(this); - - if (!this.nameDB_) { - this.nameDB_ = new Names(this.RESERVED_WORDS_); - } else { - this.nameDB_.reset(); - } - this.nameDB_.setVariableMap(workspace.getVariableMap()); - this.nameDB_.populateVariables(workspace); - this.nameDB_.populateProcedures(workspace); - - this.isInitialized = true; -}; - -/** - * Prepend the generated code with the variable definitions. - * @param {string} code Generated code. - * @return {string} Completed code. - */ -Lua.finish = function(code) { - // Convert the definitions dictionary into a list. - const definitions = Object.values(this.definitions_); - // Call Blockly.CodeGenerator's finish. - code = Object.getPrototypeOf(this).finish.call(this, code); - this.isInitialized = false; - - this.nameDB_.reset(); - return definitions.join('\n\n') + '\n\n\n' + code; -}; - -/** - * Naked values are top-level blocks with outputs that aren't plugged into - * anything. In Lua, an expression is not a legal statement, so we must assign - * the value to the (conventionally ignored) _. - * http://lua-users.org/wiki/ExpressionsAsStatements - * @param {string} line Line of generated code. - * @return {string} Legal line of code. - */ -Lua.scrubNakedValue = function(line) { - return 'local _ = ' + line + '\n'; -}; - -/** - * Encode a string as a properly escaped Lua string, complete with - * quotes. - * @param {string} string Text to encode. - * @return {string} Lua string. - * @protected - */ -Lua.quote_ = function(string) { - string = string.replace(/\\/g, '\\\\') - .replace(/\n/g, '\\\n') - .replace(/'/g, '\\\''); - return '\'' + string + '\''; -}; - -/** - * Encode a string as a properly escaped multiline Lua string, complete with - * quotes. - * @param {string} string Text to encode. - * @return {string} Lua string. - * @protected - */ -Lua.multiline_quote_ = function(string) { - const lines = string.split(/\n/g).map(this.quote_); - // Join with the following, plus a newline: - // .. '\n' .. - return lines.join(' .. \'\\n\' ..\n'); -}; - -/** - * Common tasks for generating Lua from blocks. - * Handles comments for the specified block and any connected value blocks. - * Calls any statements following this block. - * @param {!Block} block The current block. - * @param {string} code The Lua code created for this block. - * @param {boolean=} opt_thisOnly True to generate code for only this statement. - * @return {string} Lua code with comments and subsequent blocks added. - * @protected - */ -Lua.scrub_ = function(block, code, opt_thisOnly) { - let commentCode = ''; - // Only collect comments for blocks that aren't inline. - if (!block.outputConnection || !block.outputConnection.targetConnection) { - // Collect comment for this block. - let comment = block.getCommentText(); - if (comment) { - comment = stringUtils.wrap(comment, this.COMMENT_WRAP - 3); - commentCode += this.prefixLines(comment, '-- ') + '\n'; + // Copy Order values onto instance for backwards compatibility + // while ensuring they are not part of the publically-advertised + // API. + // + // TODO(#7085): deprecate these in due course. (Could initially + // replace data properties with get accessors that call + // deprecate.warn().) + for (const key in Order) { + this['ORDER_' + key] = Order[key]; } - // Collect comments for all value arguments. - // Don't collect comments for nested statements. - for (let i = 0; i < block.inputList.length; i++) { - if (block.inputList[i].type === inputTypes.VALUE) { - const childBlock = block.inputList[i].connection.targetBlock(); - if (childBlock) { - comment = this.allNestedComments(childBlock); - if (comment) { - commentCode += this.prefixLines(comment, '-- '); + + // List of illegal variable names. This is not intended to be a + // security feature. Blockly is 100% client-side, so bypassing + // this list is trivial. This is intended to prevent users from + // accidentally clobbering a built-in object or function. + this.addReservedWords( + // Special character + '_,' + + // From theoriginalbit's script: + // https://github.com/espertus/blockly-lua/issues/6 + '__inext,assert,bit,colors,colours,coroutine,disk,dofile,error,fs,' + + 'fetfenv,getmetatable,gps,help,io,ipairs,keys,loadfile,loadstring,math,' + + 'native,next,os,paintutils,pairs,parallel,pcall,peripheral,print,' + + 'printError,rawequal,rawget,rawset,read,rednet,redstone,rs,select,' + + 'setfenv,setmetatable,sleep,string,table,term,textutils,tonumber,' + + 'tostring,turtle,type,unpack,vector,write,xpcall,_VERSION,__indext,' + + // Not included in the script, probably because it wasn't enabled: + 'HTTP,' + + // Keywords (http://www.lua.org/pil/1.3.html). + 'and,break,do,else,elseif,end,false,for,function,if,in,local,nil,not,' + + 'or,repeat,return,then,true,until,while,' + + // Metamethods (http://www.lua.org/manual/5.2/manual.html). + 'add,sub,mul,div,mod,pow,unm,concat,len,eq,lt,le,index,newindex,call,' + + // Basic functions (http://www.lua.org/manual/5.2/manual.html, + // section 6.1). + 'assert,collectgarbage,dofile,error,_G,getmetatable,inpairs,load,' + + 'loadfile,next,pairs,pcall,print,rawequal,rawget,rawlen,rawset,select,' + + 'setmetatable,tonumber,tostring,type,_VERSION,xpcall,' + + // Modules (http://www.lua.org/manual/5.2/manual.html, section 6.3). + 'require,package,string,table,math,bit32,io,file,os,debug' + ); + } + + /** + * Initialise the database of variable names. + * @param {!Workspace} workspace Workspace to generate code from. + */ + init(workspace) { + // Call Blockly.CodeGenerator's init. + super.init(); + + if (!this.nameDB_) { + this.nameDB_ = new Names(this.RESERVED_WORDS_); + } else { + this.nameDB_.reset(); + } + this.nameDB_.setVariableMap(workspace.getVariableMap()); + this.nameDB_.populateVariables(workspace); + this.nameDB_.populateProcedures(workspace); + + this.isInitialized = true; + }; + + /** + * Prepend the generated code with the variable definitions. + * @param {string} code Generated code. + * @return {string} Completed code. + */ + finish(code) { + // Convert the definitions dictionary into a list. + const definitions = Object.values(this.definitions_); + // Call Blockly.CodeGenerator's finish. + code = super.finish(code); + this.isInitialized = false; + + this.nameDB_.reset(); + return definitions.join('\n\n') + '\n\n\n' + code; + }; + + /** + * Naked values are top-level blocks with outputs that aren't plugged into + * anything. In Lua, an expression is not a legal statement, so we must assign + * the value to the (conventionally ignored) _. + * http://lua-users.org/wiki/ExpressionsAsStatements + * @param {string} line Line of generated code. + * @return {string} Legal line of code. + */ + scrubNakedValue(line) { + return 'local _ = ' + line + '\n'; + }; + + /** + * Encode a string as a properly escaped Lua string, complete with + * quotes. + * @param {string} string Text to encode. + * @return {string} Lua string. + * @protected + */ + quote_(string) { + string = string.replace(/\\/g, '\\\\') + .replace(/\n/g, '\\\n') + .replace(/'/g, '\\\''); + return '\'' + string + '\''; + }; + + /** + * Encode a string as a properly escaped multiline Lua string, complete with + * quotes. + * @param {string} string Text to encode. + * @return {string} Lua string. + * @protected + */ + multiline_quote_(string) { + const lines = string.split(/\n/g).map(this.quote_); + // Join with the following, plus a newline: + // .. '\n' .. + return lines.join(' .. \'\\n\' ..\n'); + }; + + /** + * Common tasks for generating Lua from blocks. + * Handles comments for the specified block and any connected value blocks. + * Calls any statements following this block. + * @param {!Block} block The current block. + * @param {string} code The Lua code created for this block. + * @param {boolean=} opt_thisOnly True to generate code for only this statement. + * @return {string} Lua code with comments and subsequent blocks added. + * @protected + */ + scrub_(block, code, opt_thisOnly) { + let commentCode = ''; + // Only collect comments for blocks that aren't inline. + if (!block.outputConnection || !block.outputConnection.targetConnection) { + // Collect comment for this block. + let comment = block.getCommentText(); + if (comment) { + comment = stringUtils.wrap(comment, this.COMMENT_WRAP - 3); + commentCode += this.prefixLines(comment, '-- ') + '\n'; + } + // Collect comments for all value arguments. + // Don't collect comments for nested statements. + for (let i = 0; i < block.inputList.length; i++) { + if (block.inputList[i].type === inputTypes.VALUE) { + const childBlock = block.inputList[i].connection.targetBlock(); + if (childBlock) { + comment = this.allNestedComments(childBlock); + if (comment) { + commentCode += this.prefixLines(comment, '-- '); + } } } } } - } - const nextBlock = block.nextConnection && block.nextConnection.targetBlock(); - const nextCode = opt_thisOnly ? '' : this.blockToCode(nextBlock); - return commentCode + code + nextCode; -}; -export {Lua as luaGenerator}; + const nextBlock = block.nextConnection && block.nextConnection.targetBlock(); + const nextCode = opt_thisOnly ? '' : this.blockToCode(nextBlock); + return commentCode + code + nextCode; + }; +} + +/** + * Lua code generator. + * @type {!LuaGenerator} + */ +export const luaGenerator = new LuaGenerator('Lua'); diff --git a/generators/lua/colour.js b/generators/lua/colour.js index d248b0f94..61ed55a7a 100644 --- a/generators/lua/colour.js +++ b/generators/lua/colour.js @@ -11,42 +11,42 @@ import * as goog from '../../closure/goog/goog.js'; goog.declareModuleId('Blockly.Lua.colour'); -import {luaGenerator as Lua} from '../lua.js'; +import {luaGenerator, Order} from '../lua.js'; -Lua.forBlock['colour_picker'] = function(block) { +luaGenerator.forBlock['colour_picker'] = function(block) { // Colour picker. - const code = Lua.quote_(block.getFieldValue('COLOUR')); - return [code, Lua.ORDER_ATOMIC]; + const code = luaGenerator.quote_(block.getFieldValue('COLOUR')); + return [code, Order.ATOMIC]; }; -Lua.forBlock['colour_random'] = function(block) { +luaGenerator.forBlock['colour_random'] = function(block) { // Generate a random colour. const code = 'string.format("#%06x", math.random(0, 2^24 - 1))'; - return [code, Lua.ORDER_HIGH]; + return [code, Order.HIGH]; }; -Lua.forBlock['colour_rgb'] = function(block) { +luaGenerator.forBlock['colour_rgb'] = function(block) { // Compose a colour from RGB components expressed as percentages. - const functionName = Lua.provideFunction_('colour_rgb', ` -function ${Lua.FUNCTION_NAME_PLACEHOLDER_}(r, g, b) + const functionName = luaGenerator.provideFunction_('colour_rgb', ` +function ${luaGenerator.FUNCTION_NAME_PLACEHOLDER_}(r, g, b) r = math.floor(math.min(100, math.max(0, r)) * 2.55 + .5) g = math.floor(math.min(100, math.max(0, g)) * 2.55 + .5) b = math.floor(math.min(100, math.max(0, b)) * 2.55 + .5) return string.format("#%02x%02x%02x", r, g, b) end `); - const r = Lua.valueToCode(block, 'RED', Lua.ORDER_NONE) || 0; - const g = Lua.valueToCode(block, 'GREEN', Lua.ORDER_NONE) || 0; - const b = Lua.valueToCode(block, 'BLUE', Lua.ORDER_NONE) || 0; + const r = luaGenerator.valueToCode(block, 'RED', Order.NONE) || 0; + const g = luaGenerator.valueToCode(block, 'GREEN', Order.NONE) || 0; + const b = luaGenerator.valueToCode(block, 'BLUE', Order.NONE) || 0; const code = functionName + '(' + r + ', ' + g + ', ' + b + ')'; - return [code, Lua.ORDER_HIGH]; + return [code, Order.HIGH]; }; -Lua.forBlock['colour_blend'] = function(block) { +luaGenerator.forBlock['colour_blend'] = function(block) { // Blend two colours together. - const functionName = Lua.provideFunction_('colour_blend', ` -function ${Lua.FUNCTION_NAME_PLACEHOLDER_}(colour1, colour2, ratio) + const functionName = luaGenerator.provideFunction_('colour_blend', ` +function ${luaGenerator.FUNCTION_NAME_PLACEHOLDER_}(colour1, colour2, ratio) local r1 = tonumber(string.sub(colour1, 2, 3), 16) local r2 = tonumber(string.sub(colour2, 2, 3), 16) local g1 = tonumber(string.sub(colour1, 4, 5), 16) @@ -61,11 +61,11 @@ function ${Lua.FUNCTION_NAME_PLACEHOLDER_}(colour1, colour2, ratio) end `); const colour1 = - Lua.valueToCode(block, 'COLOUR1', Lua.ORDER_NONE) || "'#000000'"; + luaGenerator.valueToCode(block, 'COLOUR1', Order.NONE) || "'#000000'"; const colour2 = - Lua.valueToCode(block, 'COLOUR2', Lua.ORDER_NONE) || "'#000000'"; - const ratio = Lua.valueToCode(block, 'RATIO', Lua.ORDER_NONE) || 0; + luaGenerator.valueToCode(block, 'COLOUR2', Order.NONE) || "'#000000'"; + const ratio = luaGenerator.valueToCode(block, 'RATIO', Order.NONE) || 0; const code = functionName + '(' + colour1 + ', ' + colour2 + ', ' + ratio + ')'; - return [code, Lua.ORDER_HIGH]; + return [code, Order.HIGH]; }; diff --git a/generators/lua/lists.js b/generators/lua/lists.js index aeed7863e..aa85bd2af 100644 --- a/generators/lua/lists.js +++ b/generators/lua/lists.js @@ -12,28 +12,29 @@ import * as goog from '../../closure/goog/goog.js'; goog.declareModuleId('Blockly.Lua.lists'); import {NameType} from '../../core/names.js'; -import {luaGenerator as Lua} from '../lua.js'; +import {luaGenerator, Order} from '../lua.js'; -Lua.forBlock['lists_create_empty'] = function(block) { +luaGenerator.forBlock['lists_create_empty'] = function(block) { // Create an empty list. - return ['{}', Lua.ORDER_HIGH]; + return ['{}', Order.HIGH]; }; -Lua.forBlock['lists_create_with'] = function(block) { +luaGenerator.forBlock['lists_create_with'] = function(block) { // Create a list with any number of elements of any type. const elements = new Array(block.itemCount_); for (let i = 0; i < block.itemCount_; i++) { - elements[i] = Lua.valueToCode(block, 'ADD' + i, Lua.ORDER_NONE) || 'None'; + elements[i] = + luaGenerator.valueToCode(block, 'ADD' + i, Order.NONE) || 'None'; } const code = '{' + elements.join(', ') + '}'; - return [code, Lua.ORDER_HIGH]; + return [code, Order.HIGH]; }; -Lua.forBlock['lists_repeat'] = function(block) { +luaGenerator.forBlock['lists_repeat'] = function(block) { // Create a list with one element repeated. - const functionName = Lua.provideFunction_('create_list_repeated', ` -function ${Lua.FUNCTION_NAME_PLACEHOLDER_}(item, count) + const functionName = luaGenerator.provideFunction_('create_list_repeated', ` +function ${luaGenerator.FUNCTION_NAME_PLACEHOLDER_}(item, count) local t = {} for i = 1, count do table.insert(t, item) @@ -41,33 +42,33 @@ function ${Lua.FUNCTION_NAME_PLACEHOLDER_}(item, count) return t end `); - const element = Lua.valueToCode(block, 'ITEM', Lua.ORDER_NONE) || 'None'; - const repeatCount = Lua.valueToCode(block, 'NUM', Lua.ORDER_NONE) || '0'; + const element = luaGenerator.valueToCode(block, 'ITEM', Order.NONE) || 'None'; + const repeatCount = luaGenerator.valueToCode(block, 'NUM', Order.NONE) || '0'; const code = functionName + '(' + element + ', ' + repeatCount + ')'; - return [code, Lua.ORDER_HIGH]; + return [code, Order.HIGH]; }; -Lua.forBlock['lists_length'] = function(block) { +luaGenerator.forBlock['lists_length'] = function(block) { // String or array length. - const list = Lua.valueToCode(block, 'VALUE', Lua.ORDER_UNARY) || '{}'; - return ['#' + list, Lua.ORDER_UNARY]; + const list = luaGenerator.valueToCode(block, 'VALUE', Order.UNARY) || '{}'; + return ['#' + list, Order.UNARY]; }; -Lua.forBlock['lists_isEmpty'] = function(block) { +luaGenerator.forBlock['lists_isEmpty'] = function(block) { // Is the string null or array empty? - const list = Lua.valueToCode(block, 'VALUE', Lua.ORDER_UNARY) || '{}'; + const list = luaGenerator.valueToCode(block, 'VALUE', Order.UNARY) || '{}'; const code = '#' + list + ' == 0'; - return [code, Lua.ORDER_RELATIONAL]; + return [code, Order.RELATIONAL]; }; -Lua.forBlock['lists_indexOf'] = function(block) { +luaGenerator.forBlock['lists_indexOf'] = function(block) { // Find an item in the list. - const item = Lua.valueToCode(block, 'FIND', Lua.ORDER_NONE) || "''"; - const list = Lua.valueToCode(block, 'VALUE', Lua.ORDER_NONE) || '{}'; + const item = luaGenerator.valueToCode(block, 'FIND', Order.NONE) || "''"; + const list = luaGenerator.valueToCode(block, 'VALUE', Order.NONE) || '{}'; let functionName; if (block.getFieldValue('END') === 'FIRST') { - functionName = Lua.provideFunction_('first_index', ` -function ${Lua.FUNCTION_NAME_PLACEHOLDER_}(t, elem) + functionName = luaGenerator.provideFunction_('first_index', ` +function ${luaGenerator.FUNCTION_NAME_PLACEHOLDER_}(t, elem) for k, v in ipairs(t) do if v == elem then return k @@ -77,8 +78,8 @@ function ${Lua.FUNCTION_NAME_PLACEHOLDER_}(t, elem) end `); } else { - functionName = Lua.provideFunction_('last_index', ` -function ${Lua.FUNCTION_NAME_PLACEHOLDER_}(t, elem) + functionName = luaGenerator.provideFunction_('last_index', ` +function ${luaGenerator.FUNCTION_NAME_PLACEHOLDER_}(t, elem) for i = #t, 1, -1 do if t[i] == elem then return i @@ -89,7 +90,7 @@ end `); } const code = functionName + '(' + list + ', ' + item + ')'; - return [code, Lua.ORDER_HIGH]; + return [code, Order.HIGH]; }; /** @@ -113,12 +114,12 @@ const getListIndex = function(listName, where, opt_at) { } }; -Lua.forBlock['lists_getIndex'] = function(block) { +luaGenerator.forBlock['lists_getIndex'] = function(block) { // Get element at index. // Note: Until January 2013 this block did not have MODE or WHERE inputs. const mode = block.getFieldValue('MODE') || 'GET'; const where = block.getFieldValue('WHERE') || 'FROM_START'; - const list = Lua.valueToCode(block, 'VALUE', Lua.ORDER_HIGH) || '({})'; + const list = luaGenerator.valueToCode(block, 'VALUE', Order.HIGH) || '({})'; // If `list` would be evaluated more than once (which is the case for LAST, // FROM_END, and RANDOM) and is non-trivial, make sure to access it only once. @@ -128,21 +129,22 @@ Lua.forBlock['lists_getIndex'] = function(block) { if (mode === 'REMOVE') { // We can use multiple statements. const atOrder = - (where === 'FROM_END') ? Lua.ORDER_ADDITIVE : Lua.ORDER_NONE; - let at = Lua.valueToCode(block, 'AT', atOrder) || '1'; + (where === 'FROM_END') ? Order.ADDITIVE : Order.NONE; + let at = luaGenerator.valueToCode(block, 'AT', atOrder) || '1'; const listVar = - Lua.nameDB_.getDistinctName('tmp_list', NameType.VARIABLE); + luaGenerator.nameDB_.getDistinctName('tmp_list', NameType.VARIABLE); at = getListIndex(listVar, where, at); const code = listVar + ' = ' + list + '\n' + 'table.remove(' + listVar + ', ' + at + ')\n'; return code; } else { // We need to create a procedure to avoid reevaluating values. - const at = Lua.valueToCode(block, 'AT', Lua.ORDER_NONE) || '1'; + const at = luaGenerator.valueToCode(block, 'AT', Order.NONE) || '1'; let functionName; if (mode === 'GET') { - functionName = Lua.provideFunction_('list_get_' + where.toLowerCase(), [ - 'function ' + Lua.FUNCTION_NAME_PLACEHOLDER_ + '(t' + + functionName = luaGenerator.provideFunction_( + 'list_get_' + where.toLowerCase(), [ + 'function ' + luaGenerator.FUNCTION_NAME_PLACEHOLDER_ + '(t' + // The value for 'FROM_END' and'FROM_START' depends on `at` so // we add it as a parameter. ((where === 'FROM_END' || where === 'FROM_START') ? ', at)' : @@ -151,8 +153,9 @@ Lua.forBlock['lists_getIndex'] = function(block) { ]); } else { // `mode` === 'GET_REMOVE' functionName = - Lua.provideFunction_('list_remove_' + where.toLowerCase(), [ - 'function ' + Lua.FUNCTION_NAME_PLACEHOLDER_ + '(t' + + luaGenerator.provideFunction_( + 'list_remove_' + where.toLowerCase(), [ + 'function ' + luaGenerator.FUNCTION_NAME_PLACEHOLDER_ + '(t' + // The value for 'FROM_END' and'FROM_START' depends on `at` so // we add it as a parameter. ((where === 'FROM_END' || where === 'FROM_START') ? ', at)' : @@ -167,23 +170,23 @@ Lua.forBlock['lists_getIndex'] = function(block) { // pass it. ((where === 'FROM_END' || where === 'FROM_START') ? ', ' + at : '') + ')'; - return [code, Lua.ORDER_HIGH]; + return [code, Order.HIGH]; } } else { // Either `list` is a simple variable, or we only need to refer to `list` // once. const atOrder = (mode === 'GET' && where === 'FROM_END') ? - Lua.ORDER_ADDITIVE : - Lua.ORDER_NONE; - let at = Lua.valueToCode(block, 'AT', atOrder) || '1'; + Order.ADDITIVE : + Order.NONE; + let at = luaGenerator.valueToCode(block, 'AT', atOrder) || '1'; at = getListIndex(list, where, at); if (mode === 'GET') { const code = list + '[' + at + ']'; - return [code, Lua.ORDER_HIGH]; + return [code, Order.HIGH]; } else { const code = 'table.remove(' + list + ', ' + at + ')'; if (mode === 'GET_REMOVE') { - return [code, Lua.ORDER_HIGH]; + return [code, Order.HIGH]; } else { // `mode` === 'REMOVE' return code + '\n'; } @@ -191,14 +194,14 @@ Lua.forBlock['lists_getIndex'] = function(block) { } }; -Lua.forBlock['lists_setIndex'] = function(block) { +luaGenerator.forBlock['lists_setIndex'] = function(block) { // Set element at index. // Note: Until February 2013 this block did not have MODE or WHERE inputs. - let list = Lua.valueToCode(block, 'LIST', Lua.ORDER_HIGH) || '{}'; + let list = luaGenerator.valueToCode(block, 'LIST', Order.HIGH) || '{}'; const mode = block.getFieldValue('MODE') || 'SET'; const where = block.getFieldValue('WHERE') || 'FROM_START'; - const at = Lua.valueToCode(block, 'AT', Lua.ORDER_ADDITIVE) || '1'; - const value = Lua.valueToCode(block, 'TO', Lua.ORDER_NONE) || 'None'; + const at = luaGenerator.valueToCode(block, 'AT', Order.ADDITIVE) || '1'; + const value = luaGenerator.valueToCode(block, 'TO', Order.NONE) || 'None'; let code = ''; // If `list` would be evaluated more than once (which is the case for LAST, @@ -207,7 +210,8 @@ Lua.forBlock['lists_setIndex'] = function(block) { !list.match(/^\w+$/)) { // `list` is an expression, so we may not evaluate it more than once. // We can use multiple statements. - const listVar = Lua.nameDB_.getDistinctName('tmp_list', NameType.VARIABLE); + const listVar = + luaGenerator.nameDB_.getDistinctName('tmp_list', NameType.VARIABLE); code = listVar + ' = ' + list + '\n'; list = listVar; } @@ -223,13 +227,13 @@ Lua.forBlock['lists_setIndex'] = function(block) { return code + '\n'; }; -Lua.forBlock['lists_getSublist'] = function(block) { +luaGenerator.forBlock['lists_getSublist'] = function(block) { // Get sublist. - const list = Lua.valueToCode(block, 'LIST', Lua.ORDER_NONE) || '{}'; + const list = luaGenerator.valueToCode(block, 'LIST', Order.NONE) || '{}'; const where1 = block.getFieldValue('WHERE1'); const where2 = block.getFieldValue('WHERE2'); - const at1 = Lua.valueToCode(block, 'AT1', Lua.ORDER_NONE) || '1'; - const at2 = Lua.valueToCode(block, 'AT2', Lua.ORDER_NONE) || '1'; + const at1 = luaGenerator.valueToCode(block, 'AT1', Order.NONE) || '1'; + const at2 = luaGenerator.valueToCode(block, 'AT2', Order.NONE) || '1'; // The value for 'FROM_END' and'FROM_START' depends on `at` so // we add it as a parameter. @@ -237,9 +241,9 @@ Lua.forBlock['lists_getSublist'] = function(block) { (where1 === 'FROM_END' || where1 === 'FROM_START') ? ', at1' : ''; const at2Param = (where2 === 'FROM_END' || where2 === 'FROM_START') ? ', at2' : ''; - const functionName = Lua.provideFunction_( + const functionName = luaGenerator.provideFunction_( 'list_sublist_' + where1.toLowerCase() + '_' + where2.toLowerCase(), ` -function ${Lua.FUNCTION_NAME_PLACEHOLDER_}(source${at1Param}${at2Param}) +function ${luaGenerator.FUNCTION_NAME_PLACEHOLDER_}(source${at1Param}${at2Param}) local t = {} local start = ${getListIndex('source', where1, 'at1')} local finish = ${getListIndex('source', where2, 'at2')} @@ -255,17 +259,17 @@ end ((where1 === 'FROM_END' || where1 === 'FROM_START') ? ', ' + at1 : '') + ((where2 === 'FROM_END' || where2 === 'FROM_START') ? ', ' + at2 : '') + ')'; - return [code, Lua.ORDER_HIGH]; + return [code, Order.HIGH]; }; -Lua.forBlock['lists_sort'] = function(block) { +luaGenerator.forBlock['lists_sort'] = function(block) { // Block for sorting a list. - const list = Lua.valueToCode(block, 'LIST', Lua.ORDER_NONE) || '{}'; + const list = luaGenerator.valueToCode(block, 'LIST', Order.NONE) || '{}'; const direction = block.getFieldValue('DIRECTION') === '1' ? 1 : -1; const type = block.getFieldValue('TYPE'); - const functionName = Lua.provideFunction_('list_sort', ` -function ${Lua.FUNCTION_NAME_PLACEHOLDER_}(list, typev, direction) + const functionName = luaGenerator.provideFunction_('list_sort', ` +function ${luaGenerator.FUNCTION_NAME_PLACEHOLDER_}(list, typev, direction) local t = {} for n,v in pairs(list) do table.insert(t, v) end local compareFuncs = { @@ -289,21 +293,22 @@ end const code = functionName + '(' + list + ',"' + type + '", ' + direction + ')'; - return [code, Lua.ORDER_HIGH]; + return [code, Order.HIGH]; }; -Lua.forBlock['lists_split'] = function(block) { +luaGenerator.forBlock['lists_split'] = function(block) { // Block for splitting text into a list, or joining a list into text. - let input = Lua.valueToCode(block, 'INPUT', Lua.ORDER_NONE); - const delimiter = Lua.valueToCode(block, 'DELIM', Lua.ORDER_NONE) || "''"; + let input = luaGenerator.valueToCode(block, 'INPUT', Order.NONE); + const delimiter = + luaGenerator.valueToCode(block, 'DELIM', Order.NONE) || "''"; const mode = block.getFieldValue('MODE'); let functionName; if (mode === 'SPLIT') { if (!input) { input = "''"; } - functionName = Lua.provideFunction_('list_string_split', ` -function ${Lua.FUNCTION_NAME_PLACEHOLDER_}(input, delim) + functionName = luaGenerator.provideFunction_('list_string_split', ` +function ${luaGenerator.FUNCTION_NAME_PLACEHOLDER_}(input, delim) local t = {} local pos = 1 while true do @@ -328,14 +333,14 @@ end throw Error('Unknown mode: ' + mode); } const code = functionName + '(' + input + ', ' + delimiter + ')'; - return [code, Lua.ORDER_HIGH]; + return [code, Order.HIGH]; }; -Lua.forBlock['lists_reverse'] = function(block) { +luaGenerator.forBlock['lists_reverse'] = function(block) { // Block for reversing a list. - const list = Lua.valueToCode(block, 'LIST', Lua.ORDER_NONE) || '{}'; - const functionName = Lua.provideFunction_('list_reverse', ` -function ${Lua.FUNCTION_NAME_PLACEHOLDER_}(input) + const list = luaGenerator.valueToCode(block, 'LIST', Order.NONE) || '{}'; + const functionName = luaGenerator.provideFunction_('list_reverse', ` +function ${luaGenerator.FUNCTION_NAME_PLACEHOLDER_}(input) local reversed = {} for i = #input, 1, -1 do table.insert(reversed, input[i]) @@ -344,5 +349,5 @@ function ${Lua.FUNCTION_NAME_PLACEHOLDER_}(input) end `); const code = functionName + '(' + list + ')'; - return [code, Lua.ORDER_HIGH]; + return [code, Order.HIGH]; }; diff --git a/generators/lua/logic.js b/generators/lua/logic.js index 40cb8f173..759e461bc 100644 --- a/generators/lua/logic.js +++ b/generators/lua/logic.js @@ -11,35 +11,39 @@ import * as goog from '../../closure/goog/goog.js'; goog.declareModuleId('Blockly.Lua.logic'); -import {luaGenerator as Lua} from '../lua.js'; +import {luaGenerator, Order} from '../lua.js'; -Lua.forBlock['controls_if'] = function(block) { +luaGenerator.forBlock['controls_if'] = function(block) { // If/elseif/else condition. let n = 0; let code = ''; - if (Lua.STATEMENT_PREFIX) { + if (luaGenerator.STATEMENT_PREFIX) { // Automatic prefix insertion is switched off for this block. Add manually. - code += Lua.injectId(Lua.STATEMENT_PREFIX, block); + code += luaGenerator.injectId(luaGenerator.STATEMENT_PREFIX, block); } do { const conditionCode = - Lua.valueToCode(block, 'IF' + n, Lua.ORDER_NONE) || 'false'; - let branchCode = Lua.statementToCode(block, 'DO' + n); - if (Lua.STATEMENT_SUFFIX) { - branchCode = Lua.prefixLines( - Lua.injectId(Lua.STATEMENT_SUFFIX, block), Lua.INDENT) + branchCode; + luaGenerator.valueToCode(block, 'IF' + n, Order.NONE) || 'false'; + let branchCode = luaGenerator.statementToCode(block, 'DO' + n); + if (luaGenerator.STATEMENT_SUFFIX) { + branchCode = luaGenerator.prefixLines( + luaGenerator.injectId(luaGenerator.STATEMENT_SUFFIX, block), + luaGenerator.INDENT) + branchCode; } code += (n > 0 ? 'else' : '') + 'if ' + conditionCode + ' then\n' + branchCode; n++; } while (block.getInput('IF' + n)); - if (block.getInput('ELSE') || Lua.STATEMENT_SUFFIX) { - let branchCode = Lua.statementToCode(block, 'ELSE'); - if (Lua.STATEMENT_SUFFIX) { - branchCode = Lua.prefixLines( - Lua.injectId(Lua.STATEMENT_SUFFIX, block), Lua.INDENT) + + if (block.getInput('ELSE') || luaGenerator.STATEMENT_SUFFIX) { + let branchCode = luaGenerator.statementToCode(block, 'ELSE'); + if (luaGenerator.STATEMENT_SUFFIX) { + branchCode = + luaGenerator.prefixLines( + luaGenerator.injectId( + luaGenerator.STATEMENT_SUFFIX, block), + luaGenerator.INDENT) + branchCode; } code += 'else\n' + branchCode; @@ -47,25 +51,27 @@ Lua.forBlock['controls_if'] = function(block) { return code + 'end\n'; }; -Lua.forBlock['controls_ifelse'] = Lua.forBlock['controls_if']; +luaGenerator.forBlock['controls_ifelse'] = luaGenerator.forBlock['controls_if']; -Lua.forBlock['logic_compare'] = function(block) { +luaGenerator.forBlock['logic_compare'] = function(block) { // Comparison operator. const OPERATORS = {'EQ': '==', 'NEQ': '~=', 'LT': '<', 'LTE': '<=', 'GT': '>', 'GTE': '>='}; const operator = OPERATORS[block.getFieldValue('OP')]; - const argument0 = Lua.valueToCode(block, 'A', Lua.ORDER_RELATIONAL) || '0'; - const argument1 = Lua.valueToCode(block, 'B', Lua.ORDER_RELATIONAL) || '0'; + const argument0 = + luaGenerator.valueToCode(block, 'A', Order.RELATIONAL) || '0'; + const argument1 = + luaGenerator.valueToCode(block, 'B', Order.RELATIONAL) || '0'; const code = argument0 + ' ' + operator + ' ' + argument1; - return [code, Lua.ORDER_RELATIONAL]; + return [code, Order.RELATIONAL]; }; -Lua.forBlock['logic_operation'] = function(block) { +luaGenerator.forBlock['logic_operation'] = function(block) { // Operations 'and', 'or'. const operator = (block.getFieldValue('OP') === 'AND') ? 'and' : 'or'; - const order = (operator === 'and') ? Lua.ORDER_AND : Lua.ORDER_OR; - let argument0 = Lua.valueToCode(block, 'A', order); - let argument1 = Lua.valueToCode(block, 'B', order); + const order = (operator === 'and') ? Order.AND : Order.OR; + let argument0 = luaGenerator.valueToCode(block, 'A', order); + let argument1 = luaGenerator.valueToCode(block, 'B', order); if (!argument0 && !argument1) { // If there are no arguments, then the return value is false. argument0 = 'false'; @@ -84,29 +90,31 @@ Lua.forBlock['logic_operation'] = function(block) { return [code, order]; }; -Lua.forBlock['logic_negate'] = function(block) { +luaGenerator.forBlock['logic_negate'] = function(block) { // Negation. - const argument0 = Lua.valueToCode(block, 'BOOL', Lua.ORDER_UNARY) || 'true'; + const argument0 = + luaGenerator.valueToCode(block, 'BOOL', Order.UNARY) || 'true'; const code = 'not ' + argument0; - return [code, Lua.ORDER_UNARY]; + return [code, Order.UNARY]; }; -Lua.forBlock['logic_boolean'] = function(block) { +luaGenerator.forBlock['logic_boolean'] = function(block) { // Boolean values true and false. const code = (block.getFieldValue('BOOL') === 'TRUE') ? 'true' : 'false'; - return [code, Lua.ORDER_ATOMIC]; + return [code, Order.ATOMIC]; }; -Lua.forBlock['logic_null'] = function(block) { +luaGenerator.forBlock['logic_null'] = function(block) { // Null data type. - return ['nil', Lua.ORDER_ATOMIC]; + return ['nil', Order.ATOMIC]; }; -Lua.forBlock['logic_ternary'] = function(block) { +luaGenerator.forBlock['logic_ternary'] = function(block) { // Ternary operator. - const value_if = Lua.valueToCode(block, 'IF', Lua.ORDER_AND) || 'false'; - const value_then = Lua.valueToCode(block, 'THEN', Lua.ORDER_AND) || 'nil'; - const value_else = Lua.valueToCode(block, 'ELSE', Lua.ORDER_OR) || 'nil'; + const value_if = luaGenerator.valueToCode(block, 'IF', Order.AND) || 'false'; + const value_then = + luaGenerator.valueToCode(block, 'THEN', Order.AND) || 'nil'; + const value_else = luaGenerator.valueToCode(block, 'ELSE', Order.OR) || 'nil'; const code = value_if + ' and ' + value_then + ' or ' + value_else; - return [code, Lua.ORDER_OR]; + return [code, Order.OR]; }; diff --git a/generators/lua/loops.js b/generators/lua/loops.js index 748835b63..9a1b71b45 100644 --- a/generators/lua/loops.js +++ b/generators/lua/loops.js @@ -13,7 +13,7 @@ goog.declareModuleId('Blockly.Lua.loops'); import * as stringUtils from '../../core/utils/string.js'; import {NameType} from '../../core/names.js'; -import {luaGenerator as Lua} from '../lua.js'; +import {luaGenerator, Order} from '../lua.js'; /** @@ -36,13 +36,13 @@ const CONTINUE_STATEMENT = 'goto continue\n'; const addContinueLabel = function(branch) { if (branch.indexOf(CONTINUE_STATEMENT) !== -1) { // False positives are possible (e.g. a string literal), but are harmless. - return branch + Lua.INDENT + '::continue::\n'; + return branch + luaGenerator.INDENT + '::continue::\n'; } else { return branch; } }; -Lua.forBlock['controls_repeat_ext'] = function(block) { +luaGenerator.forBlock['controls_repeat_ext'] = function(block) { // Repeat n times. let repeats; if (block.getField('TIMES')) { @@ -50,33 +50,34 @@ Lua.forBlock['controls_repeat_ext'] = function(block) { repeats = String(Number(block.getFieldValue('TIMES'))); } else { // External number. - repeats = Lua.valueToCode(block, 'TIMES', Lua.ORDER_NONE) || '0'; + repeats = luaGenerator.valueToCode(block, 'TIMES', Order.NONE) || '0'; } if (stringUtils.isNumber(repeats)) { repeats = parseInt(repeats, 10); } else { repeats = 'math.floor(' + repeats + ')'; } - let branch = Lua.statementToCode(block, 'DO'); - branch = Lua.addLoopTrap(branch, block); + let branch = luaGenerator.statementToCode(block, 'DO'); + branch = luaGenerator.addLoopTrap(branch, block); branch = addContinueLabel(branch); - const loopVar = Lua.nameDB_.getDistinctName('count', NameType.VARIABLE); + const loopVar = luaGenerator.nameDB_.getDistinctName('count', NameType.VARIABLE); const code = 'for ' + loopVar + ' = 1, ' + repeats + ' do\n' + branch + 'end\n'; return code; }; -Lua.forBlock['controls_repeat'] = Lua.forBlock['controls_repeat_ext']; +luaGenerator.forBlock['controls_repeat'] = + luaGenerator.forBlock['controls_repeat_ext']; -Lua.forBlock['controls_whileUntil'] = function(block) { +luaGenerator.forBlock['controls_whileUntil'] = function(block) { // Do while/until loop. const until = block.getFieldValue('MODE') === 'UNTIL'; let argument0 = - Lua.valueToCode( - block, 'BOOL', until ? Lua.ORDER_UNARY : Lua.ORDER_NONE) || + luaGenerator.valueToCode( + block, 'BOOL', until ? Order.UNARY : Order.NONE) || 'false'; - let branch = Lua.statementToCode(block, 'DO'); - branch = Lua.addLoopTrap(branch, block); + let branch = luaGenerator.statementToCode(block, 'DO'); + branch = luaGenerator.addLoopTrap(branch, block); branch = addContinueLabel(branch); if (until) { argument0 = 'not ' + argument0; @@ -84,15 +85,16 @@ Lua.forBlock['controls_whileUntil'] = function(block) { return 'while ' + argument0 + ' do\n' + branch + 'end\n'; }; -Lua.forBlock['controls_for'] = function(block) { +luaGenerator.forBlock['controls_for'] = function(block) { // For loop. const variable0 = - Lua.nameDB_.getName(block.getFieldValue('VAR'), NameType.VARIABLE); - const startVar = Lua.valueToCode(block, 'FROM', Lua.ORDER_NONE) || '0'; - const endVar = Lua.valueToCode(block, 'TO', Lua.ORDER_NONE) || '0'; - const increment = Lua.valueToCode(block, 'BY', Lua.ORDER_NONE) || '1'; - let branch = Lua.statementToCode(block, 'DO'); - branch = Lua.addLoopTrap(branch, block); + luaGenerator.nameDB_.getName( + block.getFieldValue('VAR'), NameType.VARIABLE); + const startVar = luaGenerator.valueToCode(block, 'FROM', Order.NONE) || '0'; + const endVar = luaGenerator.valueToCode(block, 'TO', Order.NONE) || '0'; + const increment = luaGenerator.valueToCode(block, 'BY', Order.NONE) || '1'; + let branch = luaGenerator.statementToCode(block, 'DO'); + branch = luaGenerator.addLoopTrap(branch, block); branch = addContinueLabel(branch); let code = ''; let incValue; @@ -107,7 +109,8 @@ Lua.forBlock['controls_for'] = function(block) { // Determine loop direction at start, in case one of the bounds // changes during loop execution. incValue = - Lua.nameDB_.getDistinctName(variable0 + '_inc', NameType.VARIABLE); + luaGenerator.nameDB_.getDistinctName( + variable0 + '_inc', NameType.VARIABLE); code += incValue + ' = '; if (stringUtils.isNumber(increment)) { code += Math.abs(increment) + '\n'; @@ -115,7 +118,7 @@ Lua.forBlock['controls_for'] = function(block) { code += 'math.abs(' + increment + ')\n'; } code += 'if (' + startVar + ') > (' + endVar + ') then\n'; - code += Lua.INDENT + incValue + ' = -' + incValue + '\n'; + code += luaGenerator.INDENT + incValue + ' = -' + incValue + '\n'; code += 'end\n'; } code += @@ -124,38 +127,39 @@ Lua.forBlock['controls_for'] = function(block) { return code; }; -Lua.forBlock['controls_forEach'] = function(block) { +luaGenerator.forBlock['controls_forEach'] = function(block) { // For each loop. const variable0 = - Lua.nameDB_.getName(block.getFieldValue('VAR'), NameType.VARIABLE); - const argument0 = Lua.valueToCode(block, 'LIST', Lua.ORDER_NONE) || '{}'; - let branch = Lua.statementToCode(block, 'DO'); - branch = Lua.addLoopTrap(branch, block); + luaGenerator.nameDB_.getName( + block.getFieldValue('VAR'), NameType.VARIABLE); + const argument0 = luaGenerator.valueToCode(block, 'LIST', Order.NONE) || '{}'; + let branch = luaGenerator.statementToCode(block, 'DO'); + branch = luaGenerator.addLoopTrap(branch, block); branch = addContinueLabel(branch); const code = 'for _, ' + variable0 + ' in ipairs(' + argument0 + ') do \n' + branch + 'end\n'; return code; }; -Lua.forBlock['controls_flow_statements'] = function(block) { +luaGenerator.forBlock['controls_flow_statements'] = function(block) { // Flow statements: continue, break. let xfix = ''; - if (Lua.STATEMENT_PREFIX) { + if (luaGenerator.STATEMENT_PREFIX) { // Automatic prefix insertion is switched off for this block. Add manually. - xfix += Lua.injectId(Lua.STATEMENT_PREFIX, block); + xfix += luaGenerator.injectId(luaGenerator.STATEMENT_PREFIX, block); } - if (Lua.STATEMENT_SUFFIX) { + if (luaGenerator.STATEMENT_SUFFIX) { // Inject any statement suffix here since the regular one at the end // will not get executed if the break/continue is triggered. - xfix += Lua.injectId(Lua.STATEMENT_SUFFIX, block); + xfix += luaGenerator.injectId(luaGenerator.STATEMENT_SUFFIX, block); } - if (Lua.STATEMENT_PREFIX) { + if (luaGenerator.STATEMENT_PREFIX) { const loop = block.getSurroundLoop(); if (loop && !loop.suppressPrefixSuffix) { // Inject loop's statement prefix here since the regular one at the end // of the loop will not get executed if 'continue' is triggered. // In the case of 'break', a prefix is needed due to the loop's suffix. - xfix += Lua.injectId(Lua.STATEMENT_PREFIX, loop); + xfix += luaGenerator.injectId(luaGenerator.STATEMENT_PREFIX, loop); } } switch (block.getFieldValue('FLOW')) { diff --git a/generators/lua/math.js b/generators/lua/math.js index da137f51c..5b1ac2849 100644 --- a/generators/lua/math.js +++ b/generators/lua/math.js @@ -12,51 +12,51 @@ import * as goog from '../../closure/goog/goog.js'; goog.declareModuleId('Blockly.Lua.math'); import {NameType} from '../../core/names.js'; -import {luaGenerator as Lua} from '../lua.js'; +import {luaGenerator, Order} from '../lua.js'; -Lua.forBlock['math_number'] = function(block) { +luaGenerator.forBlock['math_number'] = function(block) { // Numeric value. const code = Number(block.getFieldValue('NUM')); - const order = code < 0 ? Lua.ORDER_UNARY : Lua.ORDER_ATOMIC; + const order = code < 0 ? Order.UNARY : Order.ATOMIC; return [code, order]; }; -Lua.forBlock['math_arithmetic'] = function(block) { +luaGenerator.forBlock['math_arithmetic'] = function(block) { // Basic arithmetic operators, and power. const OPERATORS = { - 'ADD': [' + ', Lua.ORDER_ADDITIVE], - 'MINUS': [' - ', Lua.ORDER_ADDITIVE], - 'MULTIPLY': [' * ', Lua.ORDER_MULTIPLICATIVE], - 'DIVIDE': [' / ', Lua.ORDER_MULTIPLICATIVE], - 'POWER': [' ^ ', Lua.ORDER_EXPONENTIATION], + 'ADD': [' + ', Order.ADDITIVE], + 'MINUS': [' - ', Order.ADDITIVE], + 'MULTIPLY': [' * ', Order.MULTIPLICATIVE], + 'DIVIDE': [' / ', Order.MULTIPLICATIVE], + 'POWER': [' ^ ', Order.EXPONENTIATION], }; const tuple = OPERATORS[block.getFieldValue('OP')]; const operator = tuple[0]; const order = tuple[1]; - const argument0 = Lua.valueToCode(block, 'A', order) || '0'; - const argument1 = Lua.valueToCode(block, 'B', order) || '0'; + const argument0 = luaGenerator.valueToCode(block, 'A', order) || '0'; + const argument1 = luaGenerator.valueToCode(block, 'B', order) || '0'; const code = argument0 + operator + argument1; return [code, order]; }; -Lua.forBlock['math_single'] = function(block) { +luaGenerator.forBlock['math_single'] = function(block) { // Math operators with single operand. const operator = block.getFieldValue('OP'); let arg; if (operator === 'NEG') { // Negation is a special case given its different operator precedence. - arg = Lua.valueToCode(block, 'NUM', Lua.ORDER_UNARY) || '0'; - return ['-' + arg, Lua.ORDER_UNARY]; + arg = luaGenerator.valueToCode(block, 'NUM', Order.UNARY) || '0'; + return ['-' + arg, Order.UNARY]; } if (operator === 'POW10') { - arg = Lua.valueToCode(block, 'NUM', Lua.ORDER_EXPONENTIATION) || '0'; - return ['10 ^ ' + arg, Lua.ORDER_EXPONENTIATION]; + arg = luaGenerator.valueToCode(block, 'NUM', Order.EXPONENTIATION) || '0'; + return ['10 ^ ' + arg, Order.EXPONENTIATION]; } if (operator === 'ROUND') { - arg = Lua.valueToCode(block, 'NUM', Lua.ORDER_ADDITIVE) || '0'; + arg = luaGenerator.valueToCode(block, 'NUM', Order.ADDITIVE) || '0'; } else { - arg = Lua.valueToCode(block, 'NUM', Lua.ORDER_NONE) || '0'; + arg = luaGenerator.valueToCode(block, 'NUM', Order.NONE) || '0'; } let code; @@ -107,43 +107,43 @@ Lua.forBlock['math_single'] = function(block) { default: throw Error('Unknown math operator: ' + operator); } - return [code, Lua.ORDER_HIGH]; + return [code, Order.HIGH]; }; -Lua.forBlock['math_constant'] = function(block) { +luaGenerator.forBlock['math_constant'] = function(block) { // Constants: PI, E, the Golden Ratio, sqrt(2), 1/sqrt(2), INFINITY. const CONSTANTS = { - 'PI': ['math.pi', Lua.ORDER_HIGH], - 'E': ['math.exp(1)', Lua.ORDER_HIGH], - 'GOLDEN_RATIO': ['(1 + math.sqrt(5)) / 2', Lua.ORDER_MULTIPLICATIVE], - 'SQRT2': ['math.sqrt(2)', Lua.ORDER_HIGH], - 'SQRT1_2': ['math.sqrt(1 / 2)', Lua.ORDER_HIGH], - 'INFINITY': ['math.huge', Lua.ORDER_HIGH], + 'PI': ['math.pi', Order.HIGH], + 'E': ['math.exp(1)', Order.HIGH], + 'GOLDEN_RATIO': ['(1 + math.sqrt(5)) / 2', Order.MULTIPLICATIVE], + 'SQRT2': ['math.sqrt(2)', Order.HIGH], + 'SQRT1_2': ['math.sqrt(1 / 2)', Order.HIGH], + 'INFINITY': ['math.huge', Order.HIGH], }; return CONSTANTS[block.getFieldValue('CONSTANT')]; }; -Lua.forBlock['math_number_property'] = function(block) { +luaGenerator.forBlock['math_number_property'] = function(block) { // Check if a number is even, odd, prime, whole, positive, or negative // or if it is divisible by certain number. Returns true or false. const PROPERTIES = { - 'EVEN': [' % 2 == 0', Lua.ORDER_MULTIPLICATIVE, Lua.ORDER_RELATIONAL], - 'ODD': [' % 2 == 1', Lua.ORDER_MULTIPLICATIVE, Lua.ORDER_RELATIONAL], - 'WHOLE': [' % 1 == 0', Lua.ORDER_MULTIPLICATIVE, Lua.ORDER_RELATIONAL], - 'POSITIVE': [' > 0', Lua.ORDER_RELATIONAL, Lua.ORDER_RELATIONAL], - 'NEGATIVE': [' < 0', Lua.ORDER_RELATIONAL, Lua.ORDER_RELATIONAL], - 'DIVISIBLE_BY': [null, Lua.ORDER_MULTIPLICATIVE, Lua.ORDER_RELATIONAL], - 'PRIME': [null, Lua.ORDER_NONE, Lua.ORDER_HIGH], + 'EVEN': [' % 2 == 0', Order.MULTIPLICATIVE, Order.RELATIONAL], + 'ODD': [' % 2 == 1', Order.MULTIPLICATIVE, Order.RELATIONAL], + 'WHOLE': [' % 1 == 0', Order.MULTIPLICATIVE, Order.RELATIONAL], + 'POSITIVE': [' > 0', Order.RELATIONAL, Order.RELATIONAL], + 'NEGATIVE': [' < 0', Order.RELATIONAL, Order.RELATIONAL], + 'DIVISIBLE_BY': [null, Order.MULTIPLICATIVE, Order.RELATIONAL], + 'PRIME': [null, Order.NONE, Order.HIGH], }; const dropdownProperty = block.getFieldValue('PROPERTY'); const [suffix, inputOrder, outputOrder] = PROPERTIES[dropdownProperty]; - const numberToCheck = Lua.valueToCode(block, 'NUMBER_TO_CHECK', + const numberToCheck = luaGenerator.valueToCode(block, 'NUMBER_TO_CHECK', inputOrder) || '0'; let code; if (dropdownProperty === 'PRIME') { // Prime is a special case as it is not a one-liner test. - const functionName = Lua.provideFunction_('math_isPrime', ` -function ${Lua.FUNCTION_NAME_PLACEHOLDER_}(n) + const functionName = luaGenerator.provideFunction_('math_isPrime', ` +function ${luaGenerator.FUNCTION_NAME_PLACEHOLDER_}(n) -- https://en.wikipedia.org/wiki/Primality_test#Naive_methods if n == 2 or n == 3 then return true @@ -164,12 +164,12 @@ end `); code = functionName + '(' + numberToCheck + ')'; } else if (dropdownProperty === 'DIVISIBLE_BY') { - const divisor = Lua.valueToCode(block, 'DIVISOR', - Lua.ORDER_MULTIPLICATIVE) || '0'; - // If 'divisor' is some code that evals to 0, Lua will produce a nan. + const divisor = luaGenerator.valueToCode(block, 'DIVISOR', + Order.MULTIPLICATIVE) || '0'; + // If 'divisor' is some code that evals to 0, luaGenerator will produce a nan. // Let's produce nil if we can determine this at compile-time. if (divisor === '0') { - return ['nil', Lua.ORDER_ATOMIC]; + return ['nil', Order.ATOMIC]; } // The normal trick to implement ?: with and/or doesn't work here: // divisor == 0 and nil or number_to_check % divisor == 0 @@ -181,29 +181,31 @@ end return [code, outputOrder]; }; -Lua.forBlock['math_change'] = function(block) { +luaGenerator.forBlock['math_change'] = function(block) { // Add to a variable in place. - const argument0 = Lua.valueToCode(block, 'DELTA', Lua.ORDER_ADDITIVE) || '0'; + const argument0 = + luaGenerator.valueToCode(block, 'DELTA', Order.ADDITIVE) || '0'; const varName = - Lua.nameDB_.getName(block.getFieldValue('VAR'), NameType.VARIABLE); + luaGenerator.nameDB_.getName( + block.getFieldValue('VAR'), NameType.VARIABLE); return varName + ' = ' + varName + ' + ' + argument0 + '\n'; }; // Rounding functions have a single operand. -Lua.forBlock['math_round'] = Lua.forBlock['math_single']; +luaGenerator.forBlock['math_round'] = luaGenerator.forBlock['math_single']; // Trigonometry functions have a single operand. -Lua.forBlock['math_trig'] = Lua.forBlock['math_single']; +luaGenerator.forBlock['math_trig'] = luaGenerator.forBlock['math_single']; -Lua.forBlock['math_on_list'] = function(block) { +luaGenerator.forBlock['math_on_list'] = function(block) { // Math functions for lists. const func = block.getFieldValue('OP'); - const list = Lua.valueToCode(block, 'LIST', Lua.ORDER_NONE) || '{}'; + const list = luaGenerator.valueToCode(block, 'LIST', Order.NONE) || '{}'; let functionName; // Functions needed in more than one case. function provideSum() { - return Lua.provideFunction_('math_sum', ` -function ${Lua.FUNCTION_NAME_PLACEHOLDER_}(t) + return luaGenerator.provideFunction_('math_sum', ` +function ${luaGenerator.FUNCTION_NAME_PLACEHOLDER_}(t) local result = 0 for _, v in ipairs(t) do result = result + v @@ -220,8 +222,8 @@ end case 'MIN': // Returns 0 for the empty list. - functionName = Lua.provideFunction_('math_min', ` -function ${Lua.FUNCTION_NAME_PLACEHOLDER_}(t) + functionName = luaGenerator.provideFunction_('math_min', ` +function ${luaGenerator.FUNCTION_NAME_PLACEHOLDER_}(t) if #t == 0 then return 0 end @@ -238,8 +240,8 @@ end case 'AVERAGE': // Returns 0 for the empty list. - functionName = Lua.provideFunction_('math_average', ` -function ${Lua.FUNCTION_NAME_PLACEHOLDER_}(t) + functionName = luaGenerator.provideFunction_('math_average', ` +function ${luaGenerator.FUNCTION_NAME_PLACEHOLDER_}(t) if #t == 0 then return 0 end @@ -250,8 +252,8 @@ end case 'MAX': // Returns 0 for the empty list. - functionName = Lua.provideFunction_('math_max', ` -function ${Lua.FUNCTION_NAME_PLACEHOLDER_}(t) + functionName = luaGenerator.provideFunction_('math_max', ` +function ${luaGenerator.FUNCTION_NAME_PLACEHOLDER_}(t) if #t == 0 then return 0 end @@ -268,8 +270,8 @@ end case 'MEDIAN': // This operation excludes non-numbers. - functionName = Lua.provideFunction_('math_median', ` -function ${Lua.FUNCTION_NAME_PLACEHOLDER_}(t) + functionName = luaGenerator.provideFunction_('math_median', ` +function ${luaGenerator.FUNCTION_NAME_PLACEHOLDER_}(t) -- Source: http://lua-users.org/wiki/SimpleStats if #t == 0 then return 0 @@ -293,9 +295,9 @@ end case 'MODE': // As a list of numbers can contain more than one mode, // the returned result is provided as an array. - // The Lua version includes non-numbers. - functionName = Lua.provideFunction_('math_modes', ` -function ${Lua.FUNCTION_NAME_PLACEHOLDER_}(t) + // The luaGenerator version includes non-numbers. + functionName = luaGenerator.provideFunction_('math_modes', ` +function ${luaGenerator.FUNCTION_NAME_PLACEHOLDER_}(t) -- Source: http://lua-users.org/wiki/SimpleStats local counts = {} for _, v in ipairs(t) do @@ -323,8 +325,8 @@ end break; case 'STD_DEV': - functionName = Lua.provideFunction_('math_standard_deviation', ` -function ${Lua.FUNCTION_NAME_PLACEHOLDER_}(t) + functionName = luaGenerator.provideFunction_('math_standard_deviation', ` +function ${luaGenerator.FUNCTION_NAME_PLACEHOLDER_}(t) local m local vm local total = 0 @@ -345,8 +347,8 @@ end break; case 'RANDOM': - functionName = Lua.provideFunction_('math_random_list', ` -function ${Lua.FUNCTION_NAME_PLACEHOLDER_}(t) + functionName = luaGenerator.provideFunction_('math_random_list', ` +function ${luaGenerator.FUNCTION_NAME_PLACEHOLDER_}(t) if #t == 0 then return nil end @@ -358,49 +360,49 @@ end default: throw Error('Unknown operator: ' + func); } - return [functionName + '(' + list + ')', Lua.ORDER_HIGH]; + return [functionName + '(' + list + ')', Order.HIGH]; }; -Lua.forBlock['math_modulo'] = function(block) { +luaGenerator.forBlock['math_modulo'] = function(block) { // Remainder computation. const argument0 = - Lua.valueToCode(block, 'DIVIDEND', Lua.ORDER_MULTIPLICATIVE) || '0'; + luaGenerator.valueToCode(block, 'DIVIDEND', Order.MULTIPLICATIVE) || '0'; const argument1 = - Lua.valueToCode(block, 'DIVISOR', Lua.ORDER_MULTIPLICATIVE) || '0'; + luaGenerator.valueToCode(block, 'DIVISOR', Order.MULTIPLICATIVE) || '0'; const code = argument0 + ' % ' + argument1; - return [code, Lua.ORDER_MULTIPLICATIVE]; + return [code, Order.MULTIPLICATIVE]; }; -Lua.forBlock['math_constrain'] = function(block) { +luaGenerator.forBlock['math_constrain'] = function(block) { // Constrain a number between two limits. - const argument0 = Lua.valueToCode(block, 'VALUE', Lua.ORDER_NONE) || '0'; + const argument0 = luaGenerator.valueToCode(block, 'VALUE', Order.NONE) || '0'; const argument1 = - Lua.valueToCode(block, 'LOW', Lua.ORDER_NONE) || '-math.huge'; + luaGenerator.valueToCode(block, 'LOW', Order.NONE) || '-math.huge'; const argument2 = - Lua.valueToCode(block, 'HIGH', Lua.ORDER_NONE) || 'math.huge'; + luaGenerator.valueToCode(block, 'HIGH', Order.NONE) || 'math.huge'; const code = 'math.min(math.max(' + argument0 + ', ' + argument1 + '), ' + argument2 + ')'; - return [code, Lua.ORDER_HIGH]; + return [code, Order.HIGH]; }; -Lua.forBlock['math_random_int'] = function(block) { +luaGenerator.forBlock['math_random_int'] = function(block) { // Random integer between [X] and [Y]. - const argument0 = Lua.valueToCode(block, 'FROM', Lua.ORDER_NONE) || '0'; - const argument1 = Lua.valueToCode(block, 'TO', Lua.ORDER_NONE) || '0'; + const argument0 = luaGenerator.valueToCode(block, 'FROM', Order.NONE) || '0'; + const argument1 = luaGenerator.valueToCode(block, 'TO', Order.NONE) || '0'; const code = 'math.random(' + argument0 + ', ' + argument1 + ')'; - return [code, Lua.ORDER_HIGH]; + return [code, Order.HIGH]; }; -Lua.forBlock['math_random_float'] = function(block) { +luaGenerator.forBlock['math_random_float'] = function(block) { // Random fraction between 0 and 1. - return ['math.random()', Lua.ORDER_HIGH]; + return ['math.random()', Order.HIGH]; }; -Lua.forBlock['math_atan2'] = function(block) { +luaGenerator.forBlock['math_atan2'] = function(block) { // Arctangent of point (X, Y) in degrees from -180 to 180. - const argument0 = Lua.valueToCode(block, 'X', Lua.ORDER_NONE) || '0'; - const argument1 = Lua.valueToCode(block, 'Y', Lua.ORDER_NONE) || '0'; + const argument0 = luaGenerator.valueToCode(block, 'X', Order.NONE) || '0'; + const argument1 = luaGenerator.valueToCode(block, 'Y', Order.NONE) || '0'; return [ - 'math.deg(math.atan2(' + argument1 + ', ' + argument0 + '))', Lua.ORDER_HIGH + 'math.deg(math.atan2(' + argument1 + ', ' + argument0 + '))', Order.HIGH ]; }; diff --git a/generators/lua/procedures.js b/generators/lua/procedures.js index 36f5f0059..93563d857 100644 --- a/generators/lua/procedures.js +++ b/generators/lua/procedures.js @@ -12,94 +12,100 @@ import * as goog from '../../closure/goog/goog.js'; goog.declareModuleId('Blockly.Lua.procedures'); import {NameType} from '../../core/names.js'; -import {luaGenerator as Lua} from '../lua.js'; +import {luaGenerator, Order} from '../lua.js'; -Lua.forBlock['procedures_defreturn'] = function(block) { +luaGenerator.forBlock['procedures_defreturn'] = function(block) { // Define a procedure with a return value. const funcName = - Lua.nameDB_.getName(block.getFieldValue('NAME'), NameType.PROCEDURE); + luaGenerator.nameDB_.getName( + block.getFieldValue('NAME'), NameType.PROCEDURE); let xfix1 = ''; - if (Lua.STATEMENT_PREFIX) { - xfix1 += Lua.injectId(Lua.STATEMENT_PREFIX, block); + if (luaGenerator.STATEMENT_PREFIX) { + xfix1 += luaGenerator.injectId(luaGenerator.STATEMENT_PREFIX, block); } - if (Lua.STATEMENT_SUFFIX) { - xfix1 += Lua.injectId(Lua.STATEMENT_SUFFIX, block); + if (luaGenerator.STATEMENT_SUFFIX) { + xfix1 += luaGenerator.injectId(luaGenerator.STATEMENT_SUFFIX, block); } if (xfix1) { - xfix1 = Lua.prefixLines(xfix1, Lua.INDENT); + xfix1 = luaGenerator.prefixLines(xfix1, luaGenerator.INDENT); } let loopTrap = ''; - if (Lua.INFINITE_LOOP_TRAP) { - loopTrap = Lua.prefixLines( - Lua.injectId(Lua.INFINITE_LOOP_TRAP, block), Lua.INDENT); + if (luaGenerator.INFINITE_LOOP_TRAP) { + loopTrap = luaGenerator.prefixLines( + luaGenerator.injectId( + luaGenerator.INFINITE_LOOP_TRAP, block), luaGenerator.INDENT); } - let branch = Lua.statementToCode(block, 'STACK'); - let returnValue = Lua.valueToCode(block, 'RETURN', Lua.ORDER_NONE) || ''; + let branch = luaGenerator.statementToCode(block, 'STACK'); + let returnValue = luaGenerator.valueToCode(block, 'RETURN', Order.NONE) || ''; let xfix2 = ''; if (branch && returnValue) { // After executing the function body, revisit this block for the return. xfix2 = xfix1; } if (returnValue) { - returnValue = Lua.INDENT + 'return ' + returnValue + '\n'; + returnValue = luaGenerator.INDENT + 'return ' + returnValue + '\n'; } else if (!branch) { branch = ''; } const args = []; const variables = block.getVars(); for (let i = 0; i < variables.length; i++) { - args[i] = Lua.nameDB_.getName(variables[i], NameType.VARIABLE); + args[i] = luaGenerator.nameDB_.getName(variables[i], NameType.VARIABLE); } let code = 'function ' + funcName + '(' + args.join(', ') + ')\n' + xfix1 + loopTrap + branch + xfix2 + returnValue + 'end\n'; - code = Lua.scrub_(block, code); + code = luaGenerator.scrub_(block, code); // Add % so as not to collide with helper functions in definitions list. - Lua.definitions_['%' + funcName] = code; + luaGenerator.definitions_['%' + funcName] = code; return null; }; // Defining a procedure without a return value uses the same generator as // a procedure with a return value. -Lua.forBlock['procedures_defnoreturn'] = Lua.forBlock['procedures_defreturn']; +luaGenerator.forBlock['procedures_defnoreturn'] = + luaGenerator.forBlock['procedures_defreturn']; -Lua.forBlock['procedures_callreturn'] = function(block) { +luaGenerator.forBlock['procedures_callreturn'] = function(block) { // Call a procedure with a return value. const funcName = - Lua.nameDB_.getName(block.getFieldValue('NAME'), NameType.PROCEDURE); + luaGenerator.nameDB_.getName( + block.getFieldValue('NAME'), NameType.PROCEDURE); const args = []; const variables = block.getVars(); for (let i = 0; i < variables.length; i++) { - args[i] = Lua.valueToCode(block, 'ARG' + i, Lua.ORDER_NONE) || 'nil'; + args[i] = luaGenerator.valueToCode(block, 'ARG' + i, Order.NONE) || 'nil'; } const code = funcName + '(' + args.join(', ') + ')'; - return [code, Lua.ORDER_HIGH]; + return [code, Order.HIGH]; }; -Lua.forBlock['procedures_callnoreturn'] = function(block) { +luaGenerator.forBlock['procedures_callnoreturn'] = function(block) { // Call a procedure with no return value. // Generated code is for a function call as a statement is the same as a // function call as a value, with the addition of line ending. - const tuple = Lua.forBlock['procedures_callreturn'](block); + const tuple = luaGenerator.forBlock['procedures_callreturn'](block); return tuple[0] + '\n'; }; -Lua.forBlock['procedures_ifreturn'] = function(block) { +luaGenerator.forBlock['procedures_ifreturn'] = function(block) { // Conditionally return value from a procedure. const condition = - Lua.valueToCode(block, 'CONDITION', Lua.ORDER_NONE) || 'false'; + luaGenerator.valueToCode(block, 'CONDITION', Order.NONE) || 'false'; let code = 'if ' + condition + ' then\n'; - if (Lua.STATEMENT_SUFFIX) { + if (luaGenerator.STATEMENT_SUFFIX) { // Inject any statement suffix here since the regular one at the end // will not get executed if the return is triggered. code += - Lua.prefixLines(Lua.injectId(Lua.STATEMENT_SUFFIX, block), Lua.INDENT); + luaGenerator.prefixLines( + luaGenerator.injectId(luaGenerator.STATEMENT_SUFFIX, block), + luaGenerator.INDENT); } if (block.hasReturnValue_) { - const value = Lua.valueToCode(block, 'VALUE', Lua.ORDER_NONE) || 'nil'; - code += Lua.INDENT + 'return ' + value + '\n'; + const value = luaGenerator.valueToCode(block, 'VALUE', Order.NONE) || 'nil'; + code += luaGenerator.INDENT + 'return ' + value + '\n'; } else { - code += Lua.INDENT + 'return\n'; + code += luaGenerator.INDENT + 'return\n'; } code += 'end\n'; return code; diff --git a/generators/lua/text.js b/generators/lua/text.js index cfdacce40..0c25a69c3 100644 --- a/generators/lua/text.js +++ b/generators/lua/text.js @@ -12,77 +12,79 @@ import * as goog from '../../closure/goog/goog.js'; goog.declareModuleId('Blockly.Lua.texts'); import {NameType} from '../../core/names.js'; -import {luaGenerator as Lua} from '../lua.js'; +import {luaGenerator, Order} from '../lua.js'; -Lua.forBlock['text'] = function(block) { +luaGenerator.forBlock['text'] = function(block) { // Text value. - const code = Lua.quote_(block.getFieldValue('TEXT')); - return [code, Lua.ORDER_ATOMIC]; + const code = luaGenerator.quote_(block.getFieldValue('TEXT')); + return [code, Order.ATOMIC]; }; -Lua.forBlock['text_multiline'] = function(block) { +luaGenerator.forBlock['text_multiline'] = function(block) { // Text value. - const code = Lua.multiline_quote_(block.getFieldValue('TEXT')); + const code = luaGenerator.multiline_quote_(block.getFieldValue('TEXT')); const order = - code.indexOf('..') !== -1 ? Lua.ORDER_CONCATENATION : Lua.ORDER_ATOMIC; + code.indexOf('..') !== -1 ? Order.CONCATENATION : Order.ATOMIC; return [code, order]; }; -Lua.forBlock['text_join'] = function(block) { +luaGenerator.forBlock['text_join'] = function(block) { // Create a string made up of any number of elements of any type. if (block.itemCount_ === 0) { - return ["''", Lua.ORDER_ATOMIC]; + return ["''", Order.ATOMIC]; } else if (block.itemCount_ === 1) { - const element = Lua.valueToCode(block, 'ADD0', Lua.ORDER_NONE) || "''"; + const element = luaGenerator.valueToCode(block, 'ADD0', Order.NONE) || "''"; const code = 'tostring(' + element + ')'; - return [code, Lua.ORDER_HIGH]; + return [code, Order.HIGH]; } else if (block.itemCount_ === 2) { const element0 = - Lua.valueToCode(block, 'ADD0', Lua.ORDER_CONCATENATION) || "''"; + luaGenerator.valueToCode(block, 'ADD0', Order.CONCATENATION) || "''"; const element1 = - Lua.valueToCode(block, 'ADD1', Lua.ORDER_CONCATENATION) || "''"; + luaGenerator.valueToCode(block, 'ADD1', Order.CONCATENATION) || "''"; const code = element0 + ' .. ' + element1; - return [code, Lua.ORDER_CONCATENATION]; + return [code, Order.CONCATENATION]; } else { const elements = []; for (let i = 0; i < block.itemCount_; i++) { - elements[i] = Lua.valueToCode(block, 'ADD' + i, Lua.ORDER_NONE) || "''"; + elements[i] = + luaGenerator.valueToCode(block, 'ADD' + i, Order.NONE) || "''"; } const code = 'table.concat({' + elements.join(', ') + '})'; - return [code, Lua.ORDER_HIGH]; + return [code, Order.HIGH]; } }; -Lua.forBlock['text_append'] = function(block) { +luaGenerator.forBlock['text_append'] = function(block) { // Append to a variable in place. const varName = - Lua.nameDB_.getName(block.getFieldValue('VAR'), NameType.VARIABLE); + luaGenerator.nameDB_.getName( + block.getFieldValue('VAR'), NameType.VARIABLE); const value = - Lua.valueToCode(block, 'TEXT', Lua.ORDER_CONCATENATION) || "''"; + luaGenerator.valueToCode(block, 'TEXT', Order.CONCATENATION) || "''"; return varName + ' = ' + varName + ' .. ' + value + '\n'; }; -Lua.forBlock['text_length'] = function(block) { +luaGenerator.forBlock['text_length'] = function(block) { // String or array length. - const text = Lua.valueToCode(block, 'VALUE', Lua.ORDER_UNARY) || "''"; - return ['#' + text, Lua.ORDER_UNARY]; + const text = luaGenerator.valueToCode(block, 'VALUE', Order.UNARY) || "''"; + return ['#' + text, Order.UNARY]; }; -Lua.forBlock['text_isEmpty'] = function(block) { +luaGenerator.forBlock['text_isEmpty'] = function(block) { // Is the string null or array empty? - const text = Lua.valueToCode(block, 'VALUE', Lua.ORDER_UNARY) || "''"; - return ['#' + text + ' == 0', Lua.ORDER_RELATIONAL]; + const text = luaGenerator.valueToCode(block, 'VALUE', Order.UNARY) || "''"; + return ['#' + text + ' == 0', Order.RELATIONAL]; }; -Lua.forBlock['text_indexOf'] = function(block) { +luaGenerator.forBlock['text_indexOf'] = function(block) { // Search the text for a substring. - const substring = Lua.valueToCode(block, 'FIND', Lua.ORDER_NONE) || "''"; - const text = Lua.valueToCode(block, 'VALUE', Lua.ORDER_NONE) || "''"; + const substring = luaGenerator.valueToCode(block, 'FIND', Order.NONE) || "''"; + const text = luaGenerator.valueToCode(block, 'VALUE', Order.NONE) || "''"; let functionName; if (block.getFieldValue('END') === 'FIRST') { - functionName = Lua.provideFunction_('firstIndexOf', ` -function ${Lua.FUNCTION_NAME_PLACEHOLDER_}(str, substr) + functionName = luaGenerator.provideFunction_('firstIndexOf', ` +function ${luaGenerator.FUNCTION_NAME_PLACEHOLDER_}(str, substr) local i = string.find(str, substr, 1, true) if i == nil then return 0 @@ -91,8 +93,8 @@ function ${Lua.FUNCTION_NAME_PLACEHOLDER_}(str, substr) end `); } else { - functionName = Lua.provideFunction_('lastIndexOf', ` -function ${Lua.FUNCTION_NAME_PLACEHOLDER_}(str, substr) + functionName = luaGenerator.provideFunction_('lastIndexOf', ` +function ${luaGenerator.FUNCTION_NAME_PLACEHOLDER_}(str, substr) local i = string.find(string.reverse(str), string.reverse(substr), 1, true) if i then return #str + 2 - i - #substr @@ -102,20 +104,20 @@ end `); } const code = functionName + '(' + text + ', ' + substring + ')'; - return [code, Lua.ORDER_HIGH]; + return [code, Order.HIGH]; }; -Lua.forBlock['text_charAt'] = function(block) { +luaGenerator.forBlock['text_charAt'] = function(block) { // Get letter at index. // Note: Until January 2013 this block did not have the WHERE input. const where = block.getFieldValue('WHERE') || 'FROM_START'; - const atOrder = (where === 'FROM_END') ? Lua.ORDER_UNARY : Lua.ORDER_NONE; - const at = Lua.valueToCode(block, 'AT', atOrder) || '1'; - const text = Lua.valueToCode(block, 'VALUE', Lua.ORDER_NONE) || "''"; + const atOrder = (where === 'FROM_END') ? Order.UNARY : Order.NONE; + const at = luaGenerator.valueToCode(block, 'AT', atOrder) || '1'; + const text = luaGenerator.valueToCode(block, 'VALUE', Order.NONE) || "''"; let code; if (where === 'RANDOM') { - const functionName = Lua.provideFunction_('text_random_letter', ` -function ${Lua.FUNCTION_NAME_PLACEHOLDER_}(str) + const functionName = luaGenerator.provideFunction_('text_random_letter', ` +function ${luaGenerator.FUNCTION_NAME_PLACEHOLDER_}(str) local index = math.random(string.len(str)) return string.sub(str, index, index) end @@ -140,25 +142,25 @@ end code = 'string.sub(' + text + ', ' + start + ', ' + start + ')'; } else { // use function to avoid reevaluation - const functionName = Lua.provideFunction_('text_char_at', ` -function ${Lua.FUNCTION_NAME_PLACEHOLDER_}(str, index) + const functionName = luaGenerator.provideFunction_('text_char_at', ` +function ${luaGenerator.FUNCTION_NAME_PLACEHOLDER_}(str, index) return string.sub(str, index, index) end `); code = functionName + '(' + text + ', ' + start + ')'; } } - return [code, Lua.ORDER_HIGH]; + return [code, Order.HIGH]; }; -Lua.forBlock['text_getSubstring'] = function(block) { +luaGenerator.forBlock['text_getSubstring'] = function(block) { // Get substring. - const text = Lua.valueToCode(block, 'STRING', Lua.ORDER_NONE) || "''"; + const text = luaGenerator.valueToCode(block, 'STRING', Order.NONE) || "''"; // Get start index. const where1 = block.getFieldValue('WHERE1'); - const at1Order = (where1 === 'FROM_END') ? Lua.ORDER_UNARY : Lua.ORDER_NONE; - const at1 = Lua.valueToCode(block, 'AT1', at1Order) || '1'; + const at1Order = (where1 === 'FROM_END') ? Order.UNARY : Order.NONE; + const at1 = luaGenerator.valueToCode(block, 'AT1', at1Order) || '1'; let start; if (where1 === 'FIRST') { start = 1; @@ -172,8 +174,8 @@ Lua.forBlock['text_getSubstring'] = function(block) { // Get end index. const where2 = block.getFieldValue('WHERE2'); - const at2Order = (where2 === 'FROM_END') ? Lua.ORDER_UNARY : Lua.ORDER_NONE; - const at2 = Lua.valueToCode(block, 'AT2', at2Order) || '1'; + const at2Order = (where2 === 'FROM_END') ? Order.UNARY : Order.NONE; + const at2 = luaGenerator.valueToCode(block, 'AT2', at2Order) || '1'; let end; if (where2 === 'LAST') { end = -1; @@ -185,13 +187,13 @@ Lua.forBlock['text_getSubstring'] = function(block) { throw Error('Unhandled option (text_getSubstring)'); } const code = 'string.sub(' + text + ', ' + start + ', ' + end + ')'; - return [code, Lua.ORDER_HIGH]; + return [code, Order.HIGH]; }; -Lua.forBlock['text_changeCase'] = function(block) { +luaGenerator.forBlock['text_changeCase'] = function(block) { // Change capitalization. const operator = block.getFieldValue('CASE'); - const text = Lua.valueToCode(block, 'TEXT', Lua.ORDER_NONE) || "''"; + const text = luaGenerator.valueToCode(block, 'TEXT', Order.NONE) || "''"; let functionName; if (operator === 'UPPERCASE') { functionName = 'string.upper'; @@ -201,8 +203,8 @@ Lua.forBlock['text_changeCase'] = function(block) { // There are shorter versions at // http://lua-users.org/wiki/SciteTitleCase // that do not preserve whitespace. - functionName = Lua.provideFunction_('text_titlecase', ` -function ${Lua.FUNCTION_NAME_PLACEHOLDER_}(str) + functionName = luaGenerator.provideFunction_('text_titlecase', ` +function ${luaGenerator.FUNCTION_NAME_PLACEHOLDER_}(str) local buf = {} local inWord = false for i = 1, #str do @@ -222,37 +224,37 @@ end `); } const code = functionName + '(' + text + ')'; - return [code, Lua.ORDER_HIGH]; + return [code, Order.HIGH]; }; -Lua.forBlock['text_trim'] = function(block) { +luaGenerator.forBlock['text_trim'] = function(block) { // Trim spaces. const OPERATORS = {LEFT: '^%s*(,-)', RIGHT: '(.-)%s*$', BOTH: '^%s*(.-)%s*$'}; const operator = OPERATORS[block.getFieldValue('MODE')]; - const text = Lua.valueToCode(block, 'TEXT', Lua.ORDER_NONE) || "''"; + const text = luaGenerator.valueToCode(block, 'TEXT', Order.NONE) || "''"; const code = 'string.gsub(' + text + ', "' + operator + '", "%1")'; - return [code, Lua.ORDER_HIGH]; + return [code, Order.HIGH]; }; -Lua.forBlock['text_print'] = function(block) { +luaGenerator.forBlock['text_print'] = function(block) { // Print statement. - const msg = Lua.valueToCode(block, 'TEXT', Lua.ORDER_NONE) || "''"; + const msg = luaGenerator.valueToCode(block, 'TEXT', Order.NONE) || "''"; return 'print(' + msg + ')\n'; }; -Lua.forBlock['text_prompt_ext'] = function(block) { +luaGenerator.forBlock['text_prompt_ext'] = function(block) { // Prompt function. let msg; if (block.getField('TEXT')) { // Internal message. - msg = Lua.quote_(block.getFieldValue('TEXT')); + msg = luaGenerator.quote_(block.getFieldValue('TEXT')); } else { // External message. - msg = Lua.valueToCode(block, 'TEXT', Lua.ORDER_NONE) || "''"; + msg = luaGenerator.valueToCode(block, 'TEXT', Order.NONE) || "''"; } - const functionName = Lua.provideFunction_('text_prompt', ` -function ${Lua.FUNCTION_NAME_PLACEHOLDER_}(msg) + const functionName = luaGenerator.provideFunction_('text_prompt', ` +function ${luaGenerator.FUNCTION_NAME_PLACEHOLDER_}(msg) io.write(msg) io.flush() return io.read() @@ -264,16 +266,16 @@ end if (toNumber) { code = 'tonumber(' + code + ', 10)'; } - return [code, Lua.ORDER_HIGH]; + return [code, Order.HIGH]; }; -Lua.forBlock['text_prompt'] = Lua.forBlock['text_prompt_ext']; +luaGenerator.forBlock['text_prompt'] = luaGenerator.forBlock['text_prompt_ext']; -Lua.forBlock['text_count'] = function(block) { - const text = Lua.valueToCode(block, 'TEXT', Lua.ORDER_NONE) || "''"; - const sub = Lua.valueToCode(block, 'SUB', Lua.ORDER_NONE) || "''"; - const functionName = Lua.provideFunction_('text_count', ` -function ${Lua.FUNCTION_NAME_PLACEHOLDER_}(haystack, needle) +luaGenerator.forBlock['text_count'] = function(block) { + const text = luaGenerator.valueToCode(block, 'TEXT', Order.NONE) || "''"; + const sub = luaGenerator.valueToCode(block, 'SUB', Order.NONE) || "''"; + const functionName = luaGenerator.provideFunction_('text_count', ` +function ${luaGenerator.FUNCTION_NAME_PLACEHOLDER_}(haystack, needle) if #needle == 0 then return #haystack + 1 end @@ -291,15 +293,15 @@ function ${Lua.FUNCTION_NAME_PLACEHOLDER_}(haystack, needle) end `); const code = functionName + '(' + text + ', ' + sub + ')'; - return [code, Lua.ORDER_HIGH]; + return [code, Order.HIGH]; }; -Lua.forBlock['text_replace'] = function(block) { - const text = Lua.valueToCode(block, 'TEXT', Lua.ORDER_NONE) || "''"; - const from = Lua.valueToCode(block, 'FROM', Lua.ORDER_NONE) || "''"; - const to = Lua.valueToCode(block, 'TO', Lua.ORDER_NONE) || "''"; - const functionName = Lua.provideFunction_('text_replace', ` -function ${Lua.FUNCTION_NAME_PLACEHOLDER_}(haystack, needle, replacement) +luaGenerator.forBlock['text_replace'] = function(block) { + const text = luaGenerator.valueToCode(block, 'TEXT', Order.NONE) || "''"; + const from = luaGenerator.valueToCode(block, 'FROM', Order.NONE) || "''"; + const to = luaGenerator.valueToCode(block, 'TO', Order.NONE) || "''"; + const functionName = luaGenerator.provideFunction_('text_replace', ` +function ${luaGenerator.FUNCTION_NAME_PLACEHOLDER_}(haystack, needle, replacement) local buf = {} local i = 1 while i <= #haystack do @@ -317,11 +319,11 @@ function ${Lua.FUNCTION_NAME_PLACEHOLDER_}(haystack, needle, replacement) end `); const code = functionName + '(' + text + ', ' + from + ', ' + to + ')'; - return [code, Lua.ORDER_HIGH]; + return [code, Order.HIGH]; }; -Lua.forBlock['text_reverse'] = function(block) { - const text = Lua.valueToCode(block, 'TEXT', Lua.ORDER_NONE) || "''"; +luaGenerator.forBlock['text_reverse'] = function(block) { + const text = luaGenerator.valueToCode(block, 'TEXT', Order.NONE) || "''"; const code = 'string.reverse(' + text + ')'; - return [code, Lua.ORDER_HIGH]; + return [code, Order.HIGH]; }; diff --git a/generators/lua/variables.js b/generators/lua/variables.js index 7d1df86ab..c125472e2 100644 --- a/generators/lua/variables.js +++ b/generators/lua/variables.js @@ -12,20 +12,22 @@ import * as goog from '../../closure/goog/goog.js'; goog.declareModuleId('Blockly.Lua.variables'); import {NameType} from '../../core/names.js'; -import {luaGenerator as Lua} from '../lua.js'; +import {luaGenerator, Order} from '../lua.js'; -Lua.forBlock['variables_get'] = function(block) { +luaGenerator.forBlock['variables_get'] = function(block) { // Variable getter. const code = - Lua.nameDB_.getName(block.getFieldValue('VAR'), NameType.VARIABLE); - return [code, Lua.ORDER_ATOMIC]; + luaGenerator.nameDB_.getName( + block.getFieldValue('VAR'), NameType.VARIABLE); + return [code, Order.ATOMIC]; }; -Lua.forBlock['variables_set'] = function(block) { +luaGenerator.forBlock['variables_set'] = function(block) { // Variable setter. - const argument0 = Lua.valueToCode(block, 'VALUE', Lua.ORDER_NONE) || '0'; + const argument0 = luaGenerator.valueToCode(block, 'VALUE', Order.NONE) || '0'; const varName = - Lua.nameDB_.getName(block.getFieldValue('VAR'), NameType.VARIABLE); + luaGenerator.nameDB_.getName( + block.getFieldValue('VAR'), NameType.VARIABLE); return varName + ' = ' + argument0 + '\n'; }; diff --git a/generators/lua/variables_dynamic.js b/generators/lua/variables_dynamic.js index df08babee..0a627fbdf 100644 --- a/generators/lua/variables_dynamic.js +++ b/generators/lua/variables_dynamic.js @@ -11,10 +11,12 @@ import * as goog from '../../closure/goog/goog.js'; goog.declareModuleId('Blockly.Lua.variablesDynamic'); -import {luaGenerator as Lua} from '../lua.js'; +import {luaGenerator} from '../lua.js'; import './variables.js'; // Lua is dynamically typed. -Lua.forBlock['variables_get_dynamic'] = Lua.forBlock['variables_get']; -Lua.forBlock['variables_set_dynamic'] = Lua.forBlock['variables_set']; +luaGenerator.forBlock['variables_get_dynamic'] = + luaGenerator.forBlock['variables_get']; +luaGenerator.forBlock['variables_set_dynamic'] = + luaGenerator.forBlock['variables_set'];