refactor: convert some block generators to goog.module (#5769)

* refactor: convert generators/lua/colour.js to goog.module

* refactor: convert generators/lua/colour.js to named requires

* chore: run clang-format

* refactor: convert generators/lua/lists.js to goog.module

* refactor: convert generators/lua/lists.js to named requires

* chore: run clang-format

* fix: use getListIndex helper function in lua list generators

* refactor: convert generators/lua/logic.js to goog.module

* refactor: convert generators/lua/logic.js to named requires

* chore: run clang-format

* refactor: convert generators/lua/loops.js to goog.module

* refactor: convert generators/lua/loops.js to named requires

* chore: run clang-format

* refactor: convert generators/lua/math.js to goog.module

* refactor: convert generators/lua/math.js to named requires

* chore: run clang-format

* refcator: convert generators/lua/procedures.js to goog.module

* refactor: convert generators/lua/procedures.js to named requires

* chore: run clang-format

* chore: rebuild deps.js

* refactor: convert generators/lua/text.js to goog.module

* refactor: convert generators/lua/text.js to named requires

* refactor: convert generators/lua/variables_dynamic.js to goog.module

* refactor: convert generators/lua/variables_dynamic.js to named requires

* chore: run clang-format on text.js

* refactor: convert generators/lua/variables.js to goog.module

* refactor: convert generators/lua/variables.js to named requires

* chore: run clang-format

* chore: make a lua generator function internal

* chore: rebuild deps.js
This commit is contained in:
Rachel Fenichel
2021-12-01 14:57:21 -08:00
committed by GitHub
parent d7b82cddfc
commit a939fec53b
10 changed files with 663 additions and 854 deletions

View File

@@ -9,67 +9,61 @@
*/ */
'use strict'; 'use strict';
goog.provide('Blockly.Lua.colour'); goog.module('Blockly.Lua.colour');
goog.require('Blockly.Lua'); const Lua = goog.require('Blockly.Lua');
Blockly.Lua['colour_picker'] = function(block) { Lua['colour_picker'] = function(block) {
// Colour picker. // Colour picker.
const code = Blockly.Lua.quote_(block.getFieldValue('COLOUR')); const code = Lua.quote_(block.getFieldValue('COLOUR'));
return [code, Blockly.Lua.ORDER_ATOMIC]; return [code, Lua.ORDER_ATOMIC];
}; };
Blockly.Lua['colour_random'] = function(block) { Lua['colour_random'] = function(block) {
// Generate a random colour. // Generate a random colour.
const code = 'string.format("#%06x", math.random(0, 2^24 - 1))'; const code = 'string.format("#%06x", math.random(0, 2^24 - 1))';
return [code, Blockly.Lua.ORDER_HIGH]; return [code, Lua.ORDER_HIGH];
}; };
Blockly.Lua['colour_rgb'] = function(block) { Lua['colour_rgb'] = function(block) {
// Compose a colour from RGB components expressed as percentages. // Compose a colour from RGB components expressed as percentages.
const functionName = Blockly.Lua.provideFunction_( const functionName = Lua.provideFunction_('colour_rgb', [
'colour_rgb', 'function ' + Lua.FUNCTION_NAME_PLACEHOLDER_ + '(r, g, b)',
['function ' + Blockly.Lua.FUNCTION_NAME_PLACEHOLDER_ + '(r, g, b)', ' r = math.floor(math.min(100, math.max(0, r)) * 2.55 + .5)',
' 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)',
' 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)',
' b = math.floor(math.min(100, math.max(0, b)) * 2.55 + .5)', ' return string.format("#%02x%02x%02x", r, g, b)', 'end'
' return string.format("#%02x%02x%02x", r, g, b)', ]);
'end']); const r = Lua.valueToCode(block, 'RED', Lua.ORDER_NONE) || 0;
const r = Blockly.Lua.valueToCode(block, 'RED', const g = Lua.valueToCode(block, 'GREEN', Lua.ORDER_NONE) || 0;
Blockly.Lua.ORDER_NONE) || 0; const b = Lua.valueToCode(block, 'BLUE', Lua.ORDER_NONE) || 0;
const g = Blockly.Lua.valueToCode(block, 'GREEN',
Blockly.Lua.ORDER_NONE) || 0;
const b = Blockly.Lua.valueToCode(block, 'BLUE',
Blockly.Lua.ORDER_NONE) || 0;
const code = functionName + '(' + r + ', ' + g + ', ' + b + ')'; const code = functionName + '(' + r + ', ' + g + ', ' + b + ')';
return [code, Blockly.Lua.ORDER_HIGH]; return [code, Lua.ORDER_HIGH];
}; };
Blockly.Lua['colour_blend'] = function(block) { Lua['colour_blend'] = function(block) {
// Blend two colours together. // Blend two colours together.
const functionName = Blockly.Lua.provideFunction_( const functionName = Lua.provideFunction_('colour_blend', [
'colour_blend', 'function ' + Lua.FUNCTION_NAME_PLACEHOLDER_ + '(colour1, colour2, ratio)',
['function ' + Blockly.Lua.FUNCTION_NAME_PLACEHOLDER_ + ' local r1 = tonumber(string.sub(colour1, 2, 3), 16)',
'(colour1, colour2, ratio)', ' local r2 = tonumber(string.sub(colour2, 2, 3), 16)',
' local r1 = tonumber(string.sub(colour1, 2, 3), 16)', ' local g1 = tonumber(string.sub(colour1, 4, 5), 16)',
' local r2 = tonumber(string.sub(colour2, 2, 3), 16)', ' local g2 = tonumber(string.sub(colour2, 4, 5), 16)',
' local g1 = tonumber(string.sub(colour1, 4, 5), 16)', ' local b1 = tonumber(string.sub(colour1, 6, 7), 16)',
' local g2 = tonumber(string.sub(colour2, 4, 5), 16)', ' local b2 = tonumber(string.sub(colour2, 6, 7), 16)',
' local b1 = tonumber(string.sub(colour1, 6, 7), 16)', ' local ratio = math.min(1, math.max(0, ratio))',
' local b2 = tonumber(string.sub(colour2, 6, 7), 16)', ' local r = math.floor(r1 * (1 - ratio) + r2 * ratio + .5)',
' local ratio = math.min(1, math.max(0, ratio))', ' local g = math.floor(g1 * (1 - ratio) + g2 * ratio + .5)',
' local r = math.floor(r1 * (1 - ratio) + r2 * ratio + .5)', ' local b = math.floor(b1 * (1 - ratio) + b2 * ratio + .5)',
' local g = math.floor(g1 * (1 - ratio) + g2 * ratio + .5)', ' return string.format("#%02x%02x%02x", r, g, b)', 'end'
' local b = math.floor(b1 * (1 - ratio) + b2 * ratio + .5)', ]);
' return string.format("#%02x%02x%02x", r, g, b)', const colour1 =
'end']); Lua.valueToCode(block, 'COLOUR1', Lua.ORDER_NONE) || '\'#000000\'';
const colour1 = Blockly.Lua.valueToCode(block, 'COLOUR1', const colour2 =
Blockly.Lua.ORDER_NONE) || '\'#000000\''; Lua.valueToCode(block, 'COLOUR2', Lua.ORDER_NONE) || '\'#000000\'';
const colour2 = Blockly.Lua.valueToCode(block, 'COLOUR2', const ratio = Lua.valueToCode(block, 'RATIO', Lua.ORDER_NONE) || 0;
Blockly.Lua.ORDER_NONE) || '\'#000000\''; const code =
const ratio = Blockly.Lua.valueToCode(block, 'RATIO', functionName + '(' + colour1 + ', ' + colour2 + ', ' + ratio + ')';
Blockly.Lua.ORDER_NONE) || 0; return [code, Lua.ORDER_HIGH];
const code = functionName + '(' + colour1 + ', ' + colour2 + ', ' + ratio + ')';
return [code, Blockly.Lua.ORDER_HIGH];
}; };

View File

@@ -6,97 +6,76 @@
/** /**
* @fileoverview Generating Lua for list blocks. * @fileoverview Generating Lua for list blocks.
* @suppress {missingRequire}
*/ */
'use strict'; 'use strict';
goog.provide('Blockly.Lua.lists'); goog.module('Blockly.Lua.lists');
goog.require('Blockly.Lua'); const Lua = goog.require('Blockly.Lua');
const {NameType} = goog.require('Blockly.Names');
Blockly.Lua['lists_create_empty'] = function(block) { Lua['lists_create_empty'] = function(block) {
// Create an empty list. // Create an empty list.
return ['{}', Blockly.Lua.ORDER_HIGH]; return ['{}', Lua.ORDER_HIGH];
}; };
Blockly.Lua['lists_create_with'] = function(block) { Lua['lists_create_with'] = function(block) {
// Create a list with any number of elements of any type. // Create a list with any number of elements of any type.
const elements = new Array(block.itemCount_); const elements = new Array(block.itemCount_);
for (let i = 0; i < block.itemCount_; i++) { for (let i = 0; i < block.itemCount_; i++) {
elements[i] = Blockly.Lua.valueToCode(block, 'ADD' + i, elements[i] = Lua.valueToCode(block, 'ADD' + i, Lua.ORDER_NONE) || 'None';
Blockly.Lua.ORDER_NONE) || 'None';
} }
const code = '{' + elements.join(', ') + '}'; const code = '{' + elements.join(', ') + '}';
return [code, Blockly.Lua.ORDER_HIGH]; return [code, Lua.ORDER_HIGH];
}; };
Blockly.Lua['lists_repeat'] = function(block) { Lua['lists_repeat'] = function(block) {
// Create a list with one element repeated. // Create a list with one element repeated.
const functionName = Blockly.Lua.provideFunction_( const functionName = Lua.provideFunction_('create_list_repeated', [
'create_list_repeated', 'function ' + Lua.FUNCTION_NAME_PLACEHOLDER_ + '(item, count)',
['function ' + Blockly.Lua.FUNCTION_NAME_PLACEHOLDER_ + '(item, count)', ' local t = {}', ' for i = 1, count do', ' table.insert(t, item)',
' local t = {}', ' end', ' return t', 'end'
' for i = 1, count do', ]);
' table.insert(t, item)', const element = Lua.valueToCode(block, 'ITEM', Lua.ORDER_NONE) || 'None';
' end', const repeatCount = Lua.valueToCode(block, 'NUM', Lua.ORDER_NONE) || '0';
' return t',
'end']);
const element = Blockly.Lua.valueToCode(block, 'ITEM',
Blockly.Lua.ORDER_NONE) || 'None';
const repeatCount = Blockly.Lua.valueToCode(block, 'NUM',
Blockly.Lua.ORDER_NONE) || '0';
const code = functionName + '(' + element + ', ' + repeatCount + ')'; const code = functionName + '(' + element + ', ' + repeatCount + ')';
return [code, Blockly.Lua.ORDER_HIGH]; return [code, Lua.ORDER_HIGH];
}; };
Blockly.Lua['lists_length'] = function(block) { Lua['lists_length'] = function(block) {
// String or array length. // String or array length.
const list = Blockly.Lua.valueToCode(block, 'VALUE', const list = Lua.valueToCode(block, 'VALUE', Lua.ORDER_UNARY) || '{}';
Blockly.Lua.ORDER_UNARY) || '{}'; return ['#' + list, Lua.ORDER_UNARY];
return ['#' + list, Blockly.Lua.ORDER_UNARY];
}; };
Blockly.Lua['lists_isEmpty'] = function(block) { Lua['lists_isEmpty'] = function(block) {
// Is the string null or array empty? // Is the string null or array empty?
const list = Blockly.Lua.valueToCode(block, 'VALUE', const list = Lua.valueToCode(block, 'VALUE', Lua.ORDER_UNARY) || '{}';
Blockly.Lua.ORDER_UNARY) || '{}';
const code = '#' + list + ' == 0'; const code = '#' + list + ' == 0';
return [code, Blockly.Lua.ORDER_RELATIONAL]; return [code, Lua.ORDER_RELATIONAL];
}; };
Blockly.Lua['lists_indexOf'] = function(block) { Lua['lists_indexOf'] = function(block) {
// Find an item in the list. // Find an item in the list.
const item = Blockly.Lua.valueToCode(block, 'FIND', const item = Lua.valueToCode(block, 'FIND', Lua.ORDER_NONE) || '\'\'';
Blockly.Lua.ORDER_NONE) || '\'\''; const list = Lua.valueToCode(block, 'VALUE', Lua.ORDER_NONE) || '{}';
const list = Blockly.Lua.valueToCode(block, 'VALUE',
Blockly.Lua.ORDER_NONE) || '{}';
let functionName; let functionName;
if (block.getFieldValue('END') === 'FIRST') { if (block.getFieldValue('END') === 'FIRST') {
functionName = Blockly.Lua.provideFunction_( functionName = Lua.provideFunction_('first_index', [
'first_index', 'function ' + Lua.FUNCTION_NAME_PLACEHOLDER_ + '(t, elem)',
['function ' + Blockly.Lua.FUNCTION_NAME_PLACEHOLDER_ + '(t, elem)', ' for k, v in ipairs(t) do', ' if v == elem then', ' return k',
' for k, v in ipairs(t) do', ' end', ' end', ' return 0', 'end'
' if v == elem then', ]);
' return k',
' end',
' end',
' return 0',
'end']);
} else { } else {
functionName = Blockly.Lua.provideFunction_( functionName = Lua.provideFunction_('last_index', [
'last_index', 'function ' + Lua.FUNCTION_NAME_PLACEHOLDER_ + '(t, elem)',
['function ' + Blockly.Lua.FUNCTION_NAME_PLACEHOLDER_ + '(t, elem)', ' for i = #t, 1, -1 do', ' if t[i] == elem then', ' return i',
' for i = #t, 1, -1 do', ' end', ' end', ' return 0', 'end'
' if t[i] == elem then', ]);
' return i',
' end',
' end',
' return 0',
'end']);
} }
const code = functionName + '(' + list + ', ' + item + ')'; const code = functionName + '(' + list + ', ' + item + ')';
return [code, Blockly.Lua.ORDER_HIGH]; return [code, Lua.ORDER_HIGH];
}; };
/** /**
@@ -105,9 +84,8 @@ Blockly.Lua['lists_indexOf'] = function(block) {
* @param {string} where The method of indexing, selected by dropdown in Blockly * @param {string} where The method of indexing, selected by dropdown in Blockly
* @param {string=} opt_at The optional offset when indexing from start/end. * @param {string=} opt_at The optional offset when indexing from start/end.
* @return {string|undefined} Index expression. * @return {string|undefined} Index expression.
* @private
*/ */
Blockly.Lua.lists.getIndex_ = function(listName, where, opt_at) { const getListIndex = function(listName, where, opt_at) {
if (where === 'FIRST') { if (where === 'FIRST') {
return '1'; return '1';
} else if (where === 'FROM_END') { } else if (where === 'FROM_END') {
@@ -121,14 +99,12 @@ Blockly.Lua.lists.getIndex_ = function(listName, where, opt_at) {
} }
}; };
Blockly.Lua['lists_getIndex'] = function(block) { Lua['lists_getIndex'] = function(block) {
// Get element at index. // Get element at index.
// Note: Until January 2013 this block did not have MODE or WHERE inputs. // Note: Until January 2013 this block did not have MODE or WHERE inputs.
const mode = block.getFieldValue('MODE') || 'GET'; const mode = block.getFieldValue('MODE') || 'GET';
const where = block.getFieldValue('WHERE') || 'FROM_START'; const where = block.getFieldValue('WHERE') || 'FROM_START';
const list = Blockly.Lua.valueToCode(block, 'VALUE', Blockly.Lua.ORDER_HIGH) || const list = Lua.valueToCode(block, 'VALUE', Lua.ORDER_HIGH) || '({})';
'({})';
const getIndex_ = Blockly.Lua.lists.getIndex_;
// If `list` would be evaluated more than once (which is the case for LAST, // 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. // FROM_END, and RANDOM) and is non-trivial, make sure to access it only once.
@@ -137,62 +113,63 @@ Blockly.Lua['lists_getIndex'] = function(block) {
// `list` is an expression, so we may not evaluate it more than once. // `list` is an expression, so we may not evaluate it more than once.
if (mode === 'REMOVE') { if (mode === 'REMOVE') {
// We can use multiple statements. // We can use multiple statements.
const atOrder = (where === 'FROM_END') ? Blockly.Lua.ORDER_ADDITIVE : const atOrder =
Blockly.Lua.ORDER_NONE; (where === 'FROM_END') ? Lua.ORDER_ADDITIVE : Lua.ORDER_NONE;
let at = Blockly.Lua.valueToCode(block, 'AT', atOrder) || '1'; let at = Lua.valueToCode(block, 'AT', atOrder) || '1';
const listVar = Blockly.Lua.nameDB_.getDistinctName( const listVar =
'tmp_list', Blockly.VARIABLE_CATEGORY_NAME); Lua.nameDB_.getDistinctName('tmp_list', NameType.VARIABLE);
at = getIndex_(listVar, where, at); at = getListIndex(listVar, where, at);
const code = listVar + ' = ' + list + '\n' + const code = listVar + ' = ' + list + '\n' +
'table.remove(' + listVar + ', ' + at + ')\n'; 'table.remove(' + listVar + ', ' + at + ')\n';
return code; return code;
} else { } else {
// We need to create a procedure to avoid reevaluating values. // We need to create a procedure to avoid reevaluating values.
const at = Blockly.Lua.valueToCode(block, 'AT', Blockly.Lua.ORDER_NONE) || const at = Lua.valueToCode(block, 'AT', Lua.ORDER_NONE) || '1';
'1';
let functionName; let functionName;
if (mode === 'GET') { if (mode === 'GET') {
functionName = Blockly.Lua.provideFunction_( functionName = Lua.provideFunction_('list_get_' + where.toLowerCase(), [
'list_get_' + where.toLowerCase(), 'function ' + Lua.FUNCTION_NAME_PLACEHOLDER_ + '(t' +
['function ' + Blockly.Lua.FUNCTION_NAME_PLACEHOLDER_ + '(t' + // The value for 'FROM_END' and'FROM_START' depends on `at` so
// The value for 'FROM_END' and'FROM_START' depends on `at` so // we add it as a parameter.
// we add it as a parameter. ((where === 'FROM_END' || where === 'FROM_START') ? ', at)' :
((where === 'FROM_END' || where === 'FROM_START') ? ')'),
', at)' : ')'), ' return t[' + getListIndex('t', where, 'at') + ']', 'end'
' return t[' + getIndex_('t', where, 'at') + ']', ]);
'end']);
} else { // `mode` === 'GET_REMOVE' } else { // `mode` === 'GET_REMOVE'
functionName = Blockly.Lua.provideFunction_( functionName =
'list_remove_' + where.toLowerCase(), Lua.provideFunction_('list_remove_' + where.toLowerCase(), [
['function ' + Blockly.Lua.FUNCTION_NAME_PLACEHOLDER_ + '(t' + 'function ' + Lua.FUNCTION_NAME_PLACEHOLDER_ + '(t' +
// The value for 'FROM_END' and'FROM_START' depends on `at` so // The value for 'FROM_END' and'FROM_START' depends on `at` so
// we add it as a parameter. // we add it as a parameter.
((where === 'FROM_END' || where === 'FROM_START') ? ((where === 'FROM_END' || where === 'FROM_START') ? ', at)' :
', at)' : ')'), ')'),
' return table.remove(t, ' + getIndex_('t', where, 'at') + ')', ' return table.remove(t, ' + getListIndex('t', where, 'at') +
'end']); ')',
'end'
]);
} }
const code = functionName + '(' + list + const code = functionName + '(' + list +
// The value for 'FROM_END' and 'FROM_START' depends on `at` so we // The value for 'FROM_END' and 'FROM_START' depends on `at` so we
// pass it. // pass it.
((where === 'FROM_END' || where === 'FROM_START') ? ', ' + at : '') + ((where === 'FROM_END' || where === 'FROM_START') ? ', ' + at : '') +
')'; ')';
return [code, Blockly.Lua.ORDER_HIGH]; return [code, Lua.ORDER_HIGH];
} }
} else { } else {
// Either `list` is a simple variable, or we only need to refer to `list` // Either `list` is a simple variable, or we only need to refer to `list`
// once. // once.
const atOrder = (mode === 'GET' && where === 'FROM_END') ? const atOrder = (mode === 'GET' && where === 'FROM_END') ?
Blockly.Lua.ORDER_ADDITIVE : Blockly.Lua.ORDER_NONE; Lua.ORDER_ADDITIVE :
let at = Blockly.Lua.valueToCode(block, 'AT', atOrder) || '1'; Lua.ORDER_NONE;
at = getIndex_(list, where, at); let at = Lua.valueToCode(block, 'AT', atOrder) || '1';
at = getListIndex(list, where, at);
if (mode === 'GET') { if (mode === 'GET') {
const code = list + '[' + at + ']'; const code = list + '[' + at + ']';
return [code, Blockly.Lua.ORDER_HIGH]; return [code, Lua.ORDER_HIGH];
} else { } else {
const code = 'table.remove(' + list + ', ' + at + ')'; const code = 'table.remove(' + list + ', ' + at + ')';
if (mode === 'GET_REMOVE') { if (mode === 'GET_REMOVE') {
return [code, Blockly.Lua.ORDER_HIGH]; return [code, Lua.ORDER_HIGH];
} else { // `mode` === 'REMOVE' } else { // `mode` === 'REMOVE'
return code + '\n'; return code + '\n';
} }
@@ -200,18 +177,14 @@ Blockly.Lua['lists_getIndex'] = function(block) {
} }
}; };
Blockly.Lua['lists_setIndex'] = function(block) { Lua['lists_setIndex'] = function(block) {
// Set element at index. // Set element at index.
// Note: Until February 2013 this block did not have MODE or WHERE inputs. // Note: Until February 2013 this block did not have MODE or WHERE inputs.
let list = Blockly.Lua.valueToCode(block, 'LIST', let list = Lua.valueToCode(block, 'LIST', Lua.ORDER_HIGH) || '{}';
Blockly.Lua.ORDER_HIGH) || '{}';
const mode = block.getFieldValue('MODE') || 'SET'; const mode = block.getFieldValue('MODE') || 'SET';
const where = block.getFieldValue('WHERE') || 'FROM_START'; const where = block.getFieldValue('WHERE') || 'FROM_START';
const at = Blockly.Lua.valueToCode(block, 'AT', const at = Lua.valueToCode(block, 'AT', Lua.ORDER_ADDITIVE) || '1';
Blockly.Lua.ORDER_ADDITIVE) || '1'; const value = Lua.valueToCode(block, 'TO', Lua.ORDER_NONE) || 'None';
const value = Blockly.Lua.valueToCode(block, 'TO',
Blockly.Lua.ORDER_NONE) || 'None';
const getIndex_ = Blockly.Lua.lists.getIndex_;
let code = ''; let code = '';
// If `list` would be evaluated more than once (which is the case for LAST, // If `list` would be evaluated more than once (which is the case for LAST,
@@ -220,126 +193,108 @@ Blockly.Lua['lists_setIndex'] = function(block) {
!list.match(/^\w+$/)) { !list.match(/^\w+$/)) {
// `list` is an expression, so we may not evaluate it more than once. // `list` is an expression, so we may not evaluate it more than once.
// We can use multiple statements. // We can use multiple statements.
const listVar = Blockly.Lua.nameDB_.getDistinctName( const listVar = Lua.nameDB_.getDistinctName('tmp_list', NameType.VARIABLE);
'tmp_list', Blockly.VARIABLE_CATEGORY_NAME);
code = listVar + ' = ' + list + '\n'; code = listVar + ' = ' + list + '\n';
list = listVar; list = listVar;
} }
if (mode === 'SET') { if (mode === 'SET') {
code += list + '[' + getIndex_(list, where, at) + '] = ' + value; code += list + '[' + getListIndex(list, where, at) + '] = ' + value;
} else { // `mode` === 'INSERT' } else { // `mode` === 'INSERT'
// LAST is a special case, because we want to insert // LAST is a special case, because we want to insert
// *after* not *before*, the existing last element. // *after* not *before*, the existing last element.
code += 'table.insert(' + list + ', ' + code += 'table.insert(' + list + ', ' +
(getIndex_(list, where, at) + (where === 'LAST' ? ' + 1' : '')) + (getListIndex(list, where, at) + (where === 'LAST' ? ' + 1' : '')) +
', ' + value + ')'; ', ' + value + ')';
} }
return code + '\n'; return code + '\n';
}; };
Blockly.Lua['lists_getSublist'] = function(block) { Lua['lists_getSublist'] = function(block) {
// Get sublist. // Get sublist.
const list = Blockly.Lua.valueToCode(block, 'LIST', const list = Lua.valueToCode(block, 'LIST', Lua.ORDER_NONE) || '{}';
Blockly.Lua.ORDER_NONE) || '{}';
const where1 = block.getFieldValue('WHERE1'); const where1 = block.getFieldValue('WHERE1');
const where2 = block.getFieldValue('WHERE2'); const where2 = block.getFieldValue('WHERE2');
const at1 = Blockly.Lua.valueToCode(block, 'AT1', const at1 = Lua.valueToCode(block, 'AT1', Lua.ORDER_NONE) || '1';
Blockly.Lua.ORDER_NONE) || '1'; const at2 = Lua.valueToCode(block, 'AT2', Lua.ORDER_NONE) || '1';
const at2 = Blockly.Lua.valueToCode(block, 'AT2',
Blockly.Lua.ORDER_NONE) || '1';
const getIndex_ = Blockly.Lua.lists.getIndex_;
const functionName = Blockly.Lua.provideFunction_( const functionName = Lua.provideFunction_(
'list_sublist_' + where1.toLowerCase() + '_' + where2.toLowerCase(), 'list_sublist_' + where1.toLowerCase() + '_' + where2.toLowerCase(), [
['function ' + Blockly.Lua.FUNCTION_NAME_PLACEHOLDER_ + '(source' + 'function ' + Lua.FUNCTION_NAME_PLACEHOLDER_ + '(source' +
// The value for 'FROM_END' and'FROM_START' depends on `at` so // The value for 'FROM_END' and'FROM_START' depends on `at` so
// we add it as a parameter. // we add it as a parameter.
((where1 === 'FROM_END' || where1 === 'FROM_START') ? ', at1' : '') + ((where1 === 'FROM_END' || where1 === 'FROM_START') ? ', at1' :
((where2 === 'FROM_END' || where2 === 'FROM_START') ? ', at2' : '') + '') +
')', ((where2 === 'FROM_END' || where2 === 'FROM_START') ? ', at2' :
' local t = {}', '') +
' local start = ' + getIndex_('source', where1, 'at1'), ')',
' local finish = ' + getIndex_('source', where2, 'at2'), ' local t = {}',
' for i = start, finish do', ' local start = ' + getListIndex('source', where1, 'at1'),
' table.insert(t, source[i])', ' local finish = ' + getListIndex('source', where2, 'at2'),
' end', ' for i = start, finish do', ' table.insert(t, source[i])', ' end',
' return t', ' return t', 'end'
'end']); ]);
const code = functionName + '(' + list + const code = functionName + '(' + list +
// The value for 'FROM_END' and 'FROM_START' depends on `at` so we // The value for 'FROM_END' and 'FROM_START' depends on `at` so we
// pass it. // pass it.
((where1 === 'FROM_END' || where1 === 'FROM_START') ? ', ' + at1 : '') + ((where1 === 'FROM_END' || where1 === 'FROM_START') ? ', ' + at1 : '') +
((where2 === 'FROM_END' || where2 === 'FROM_START') ? ', ' + at2 : '') + ((where2 === 'FROM_END' || where2 === 'FROM_START') ? ', ' + at2 : '') +
')'; ')';
return [code, Blockly.Lua.ORDER_HIGH]; return [code, Lua.ORDER_HIGH];
}; };
Blockly.Lua['lists_sort'] = function(block) { Lua['lists_sort'] = function(block) {
// Block for sorting a list. // Block for sorting a list.
const list = Blockly.Lua.valueToCode( const list = Lua.valueToCode(block, 'LIST', Lua.ORDER_NONE) || '{}';
block, 'LIST', Blockly.Lua.ORDER_NONE) || '{}';
const direction = block.getFieldValue('DIRECTION') === '1' ? 1 : -1; const direction = block.getFieldValue('DIRECTION') === '1' ? 1 : -1;
const type = block.getFieldValue('TYPE'); const type = block.getFieldValue('TYPE');
const functionName = Blockly.Lua.provideFunction_( const functionName = Lua.provideFunction_('list_sort', [
'list_sort', 'function ' + Lua.FUNCTION_NAME_PLACEHOLDER_ + '(list, typev, direction)',
['function ' + Blockly.Lua.FUNCTION_NAME_PLACEHOLDER_ + ' local t = {}',
'(list, typev, direction)', ' for n,v in pairs(list) do table.insert(t, v) end', // Shallow-copy.
' local t = {}', ' local compareFuncs = {',
' for n,v in pairs(list) do table.insert(t, v) end', // Shallow-copy. ' NUMERIC = function(a, b)',
' local compareFuncs = {', ' return (tonumber(tostring(a)) or 0)',
' NUMERIC = function(a, b)', ' < (tonumber(tostring(b)) or 0) end,',
' return (tonumber(tostring(a)) or 0)', ' TEXT = function(a, b)',
' < (tonumber(tostring(b)) or 0) end,', ' return tostring(a) < tostring(b) end,',
' TEXT = function(a, b)', ' IGNORE_CASE = function(a, b)',
' return tostring(a) < tostring(b) end,', ' return string.lower(tostring(a)) < string.lower(tostring(b)) end',
' IGNORE_CASE = function(a, b)', ' }',
' return string.lower(tostring(a)) < string.lower(tostring(b)) end', ' local compareTemp = compareFuncs[typev]',
' }', ' local compare = compareTemp',
' local compareTemp = compareFuncs[typev]', ' if direction == -1',
' local compare = compareTemp', ' then compare = function(a, b) return compareTemp(b, a) end',
' if direction == -1', ' end',
' then compare = function(a, b) return compareTemp(b, a) end', ' table.sort(t, compare)',
' end', ' return t',
' table.sort(t, compare)', 'end'
' return t', ]);
'end']);
const code = functionName + const code =
'(' + list + ',"' + type + '", ' + direction + ')'; functionName + '(' + list + ',"' + type + '", ' + direction + ')';
return [code, Blockly.Lua.ORDER_HIGH]; return [code, Lua.ORDER_HIGH];
}; };
Blockly.Lua['lists_split'] = function(block) { Lua['lists_split'] = function(block) {
// Block for splitting text into a list, or joining a list into text. // Block for splitting text into a list, or joining a list into text.
let input = Blockly.Lua.valueToCode(block, 'INPUT', let input = Lua.valueToCode(block, 'INPUT', Lua.ORDER_NONE);
Blockly.Lua.ORDER_NONE); const delimiter = Lua.valueToCode(block, 'DELIM', Lua.ORDER_NONE) || '\'\'';
const delimiter = Blockly.Lua.valueToCode(block, 'DELIM',
Blockly.Lua.ORDER_NONE) || '\'\'';
const mode = block.getFieldValue('MODE'); const mode = block.getFieldValue('MODE');
let functionName; let functionName;
if (mode === 'SPLIT') { if (mode === 'SPLIT') {
if (!input) { if (!input) {
input = '\'\''; input = '\'\'';
} }
functionName = Blockly.Lua.provideFunction_( functionName = Lua.provideFunction_('list_string_split', [
'list_string_split', 'function ' + Lua.FUNCTION_NAME_PLACEHOLDER_ + '(input, delim)',
['function ' + Blockly.Lua.FUNCTION_NAME_PLACEHOLDER_ + ' local t = {}', ' local pos = 1', ' while true do',
'(input, delim)', ' next_delim = string.find(input, delim, pos)',
' local t = {}', ' if next_delim == nil then',
' local pos = 1', ' table.insert(t, string.sub(input, pos))', ' break',
' while true do', ' else', ' table.insert(t, string.sub(input, pos, next_delim-1))',
' next_delim = string.find(input, delim, pos)', ' pos = next_delim + #delim', ' end', ' end', ' return t', 'end'
' if next_delim == nil then', ]);
' table.insert(t, string.sub(input, pos))',
' break',
' else',
' table.insert(t, string.sub(input, pos, next_delim-1))',
' pos = next_delim + #delim',
' end',
' end',
' return t',
'end']);
} else if (mode === 'JOIN') { } else if (mode === 'JOIN') {
if (!input) { if (!input) {
input = '{}'; input = '{}';
@@ -349,22 +304,17 @@ Blockly.Lua['lists_split'] = function(block) {
throw Error('Unknown mode: ' + mode); throw Error('Unknown mode: ' + mode);
} }
const code = functionName + '(' + input + ', ' + delimiter + ')'; const code = functionName + '(' + input + ', ' + delimiter + ')';
return [code, Blockly.Lua.ORDER_HIGH]; return [code, Lua.ORDER_HIGH];
}; };
Blockly.Lua['lists_reverse'] = function(block) { Lua['lists_reverse'] = function(block) {
// Block for reversing a list. // Block for reversing a list.
const list = Blockly.Lua.valueToCode(block, 'LIST', const list = Lua.valueToCode(block, 'LIST', Lua.ORDER_NONE) || '{}';
Blockly.Lua.ORDER_NONE) || '{}'; const functionName = Lua.provideFunction_('list_reverse', [
const functionName = Blockly.Lua.provideFunction_( 'function ' + Lua.FUNCTION_NAME_PLACEHOLDER_ + '(input)',
'list_reverse', ' local reversed = {}', ' for i = #input, 1, -1 do',
['function ' + Blockly.Lua.FUNCTION_NAME_PLACEHOLDER_ + '(input)', ' table.insert(reversed, input[i])', ' end', ' return reversed', 'end'
' local reversed = {}', ]);
' for i = #input, 1, -1 do',
' table.insert(reversed, input[i])',
' end',
' return reversed',
'end']);
const code = functionName + '(' + list + ')'; const code = functionName + '(' + list + ')';
return [code, Blockly.Lua.ORDER_HIGH]; return [code, Lua.ORDER_HIGH];
}; };

View File

@@ -9,73 +9,64 @@
*/ */
'use strict'; 'use strict';
goog.provide('Blockly.Lua.logic'); goog.module('Blockly.Lua.logic');
goog.require('Blockly.Lua'); const Lua = goog.require('Blockly.Lua');
Blockly.Lua['controls_if'] = function(block) { Lua['controls_if'] = function(block) {
// If/elseif/else condition. // If/elseif/else condition.
let n = 0; let n = 0;
let code = ''; let code = '';
if (Blockly.Lua.STATEMENT_PREFIX) { if (Lua.STATEMENT_PREFIX) {
// Automatic prefix insertion is switched off for this block. Add manually. // Automatic prefix insertion is switched off for this block. Add manually.
code += Blockly.Lua.injectId(Blockly.Lua.STATEMENT_PREFIX, block); code += Lua.injectId(Lua.STATEMENT_PREFIX, block);
} }
do { do {
const conditionCode = Blockly.Lua.valueToCode(block, 'IF' + n, const conditionCode =
Blockly.Lua.ORDER_NONE) || 'false'; Lua.valueToCode(block, 'IF' + n, Lua.ORDER_NONE) || 'false';
let branchCode = Blockly.Lua.statementToCode(block, 'DO' + n); let branchCode = Lua.statementToCode(block, 'DO' + n);
if (Blockly.Lua.STATEMENT_SUFFIX) { if (Lua.STATEMENT_SUFFIX) {
branchCode = Blockly.Lua.prefixLines( branchCode = Lua.prefixLines(
Blockly.Lua.injectId(Blockly.Lua.STATEMENT_SUFFIX, block), Lua.injectId(Lua.STATEMENT_SUFFIX, block), Lua.INDENT) +
Blockly.Lua.INDENT) + branchCode; branchCode;
} }
code += (n > 0 ? 'else' : '') + code +=
'if ' + conditionCode + ' then\n' + branchCode; (n > 0 ? 'else' : '') + 'if ' + conditionCode + ' then\n' + branchCode;
n++; n++;
} while (block.getInput('IF' + n)); } while (block.getInput('IF' + n));
if (block.getInput('ELSE') || Blockly.Lua.STATEMENT_SUFFIX) { if (block.getInput('ELSE') || Lua.STATEMENT_SUFFIX) {
let branchCode = Blockly.Lua.statementToCode(block, 'ELSE'); let branchCode = Lua.statementToCode(block, 'ELSE');
if (Blockly.Lua.STATEMENT_SUFFIX) { if (Lua.STATEMENT_SUFFIX) {
branchCode = Blockly.Lua.prefixLines( branchCode = Lua.prefixLines(
Blockly.Lua.injectId(Blockly.Lua.STATEMENT_SUFFIX, block), Lua.injectId(Lua.STATEMENT_SUFFIX, block), Lua.INDENT) +
Blockly.Lua.INDENT) + branchCode; branchCode;
} }
code += 'else\n' + branchCode; code += 'else\n' + branchCode;
} }
return code + 'end\n'; return code + 'end\n';
}; };
Blockly.Lua['controls_ifelse'] = Blockly.Lua['controls_if']; Lua['controls_ifelse'] = Lua['controls_if'];
Blockly.Lua['logic_compare'] = function(block) { Lua['logic_compare'] = function(block) {
// Comparison operator. // Comparison operator.
const OPERATORS = { const OPERATORS =
'EQ': '==', {'EQ': '==', 'NEQ': '~=', 'LT': '<', 'LTE': '<=', 'GT': '>', 'GTE': '>='};
'NEQ': '~=',
'LT': '<',
'LTE': '<=',
'GT': '>',
'GTE': '>='
};
const operator = OPERATORS[block.getFieldValue('OP')]; const operator = OPERATORS[block.getFieldValue('OP')];
const argument0 = Blockly.Lua.valueToCode(block, 'A', const argument0 = Lua.valueToCode(block, 'A', Lua.ORDER_RELATIONAL) || '0';
Blockly.Lua.ORDER_RELATIONAL) || '0'; const argument1 = Lua.valueToCode(block, 'B', Lua.ORDER_RELATIONAL) || '0';
const argument1 = Blockly.Lua.valueToCode(block, 'B',
Blockly.Lua.ORDER_RELATIONAL) || '0';
const code = argument0 + ' ' + operator + ' ' + argument1; const code = argument0 + ' ' + operator + ' ' + argument1;
return [code, Blockly.Lua.ORDER_RELATIONAL]; return [code, Lua.ORDER_RELATIONAL];
}; };
Blockly.Lua['logic_operation'] = function(block) { Lua['logic_operation'] = function(block) {
// Operations 'and', 'or'. // Operations 'and', 'or'.
const operator = (block.getFieldValue('OP') === 'AND') ? 'and' : 'or'; const operator = (block.getFieldValue('OP') === 'AND') ? 'and' : 'or';
const order = (operator === 'and') ? Blockly.Lua.ORDER_AND : const order = (operator === 'and') ? Lua.ORDER_AND : Lua.ORDER_OR;
Blockly.Lua.ORDER_OR; let argument0 = Lua.valueToCode(block, 'A', order);
let argument0 = Blockly.Lua.valueToCode(block, 'A', order); let argument1 = Lua.valueToCode(block, 'B', order);
let argument1 = Blockly.Lua.valueToCode(block, 'B', order);
if (!argument0 && !argument1) { if (!argument0 && !argument1) {
// If there are no arguments, then the return value is false. // If there are no arguments, then the return value is false.
argument0 = 'false'; argument0 = 'false';
@@ -94,33 +85,29 @@ Blockly.Lua['logic_operation'] = function(block) {
return [code, order]; return [code, order];
}; };
Blockly.Lua['logic_negate'] = function(block) { Lua['logic_negate'] = function(block) {
// Negation. // Negation.
const argument0 = Blockly.Lua.valueToCode(block, 'BOOL', const argument0 = Lua.valueToCode(block, 'BOOL', Lua.ORDER_UNARY) || 'true';
Blockly.Lua.ORDER_UNARY) || 'true';
const code = 'not ' + argument0; const code = 'not ' + argument0;
return [code, Blockly.Lua.ORDER_UNARY]; return [code, Lua.ORDER_UNARY];
}; };
Blockly.Lua['logic_boolean'] = function(block) { Lua['logic_boolean'] = function(block) {
// Boolean values true and false. // Boolean values true and false.
const code = (block.getFieldValue('BOOL') === 'TRUE') ? 'true' : 'false'; const code = (block.getFieldValue('BOOL') === 'TRUE') ? 'true' : 'false';
return [code, Blockly.Lua.ORDER_ATOMIC]; return [code, Lua.ORDER_ATOMIC];
}; };
Blockly.Lua['logic_null'] = function(block) { Lua['logic_null'] = function(block) {
// Null data type. // Null data type.
return ['nil', Blockly.Lua.ORDER_ATOMIC]; return ['nil', Lua.ORDER_ATOMIC];
}; };
Blockly.Lua['logic_ternary'] = function(block) { Lua['logic_ternary'] = function(block) {
// Ternary operator. // Ternary operator.
const value_if = Blockly.Lua.valueToCode(block, 'IF', const value_if = Lua.valueToCode(block, 'IF', Lua.ORDER_AND) || 'false';
Blockly.Lua.ORDER_AND) || 'false'; const value_then = Lua.valueToCode(block, 'THEN', Lua.ORDER_AND) || 'nil';
const value_then = Blockly.Lua.valueToCode(block, 'THEN', const value_else = Lua.valueToCode(block, 'ELSE', Lua.ORDER_OR) || 'nil';
Blockly.Lua.ORDER_AND) || 'nil';
const value_else = Blockly.Lua.valueToCode(block, 'ELSE',
Blockly.Lua.ORDER_OR) || 'nil';
const code = value_if + ' and ' + value_then + ' or ' + value_else; const code = value_if + ' and ' + value_then + ' or ' + value_else;
return [code, Blockly.Lua.ORDER_OR]; return [code, Lua.ORDER_OR];
}; };

View File

@@ -6,14 +6,14 @@
/** /**
* @fileoverview Generating Lua for loop blocks. * @fileoverview Generating Lua for loop blocks.
* @suppress {missingRequire}
*/ */
'use strict'; 'use strict';
goog.provide('Blockly.Lua.loops'); goog.module('Blockly.Lua.loops');
goog.require('Blockly.Lua'); const Lua = goog.require('Blockly.Lua');
goog.require('Blockly.utils.string'); const stringUtils = goog.require('Blockly.utils.string');
const {NameType} = goog.require('Blockly.Names');
/** /**
@@ -22,7 +22,7 @@ goog.require('Blockly.utils.string');
* the appropriate label can be put at the end of the loop body. * the appropriate label can be put at the end of the loop body.
* @const {string} * @const {string}
*/ */
Blockly.Lua.CONTINUE_STATEMENT = 'goto continue\n'; const CONTINUE_STATEMENT = 'goto continue\n';
/** /**
* If the loop body contains a "goto continue" statement, add a continue label * If the loop body contains a "goto continue" statement, add a continue label
@@ -32,18 +32,17 @@ Blockly.Lua.CONTINUE_STATEMENT = 'goto continue\n';
* *
* @param {string} branch Generated code of the loop body * @param {string} branch Generated code of the loop body
* @return {string} Generated label or '' if unnecessary * @return {string} Generated label or '' if unnecessary
* @private
*/ */
Blockly.Lua.addContinueLabel_ = function(branch) { const addContinueLabel = function(branch) {
if (branch.indexOf(Blockly.Lua.CONTINUE_STATEMENT) !== -1) { if (branch.indexOf(CONTINUE_STATEMENT) !== -1) {
// False positives are possible (e.g. a string literal), but are harmless. // False positives are possible (e.g. a string literal), but are harmless.
return branch + Blockly.Lua.INDENT + '::continue::\n'; return branch + Lua.INDENT + '::continue::\n';
} else { } else {
return branch; return branch;
} }
}; };
Blockly.Lua['controls_repeat_ext'] = function(block) { Lua['controls_repeat_ext'] = function(block) {
// Repeat n times. // Repeat n times.
let repeats; let repeats;
if (block.getField('TIMES')) { if (block.getField('TIMES')) {
@@ -51,58 +50,54 @@ Blockly.Lua['controls_repeat_ext'] = function(block) {
repeats = String(Number(block.getFieldValue('TIMES'))); repeats = String(Number(block.getFieldValue('TIMES')));
} else { } else {
// External number. // External number.
repeats = Blockly.Lua.valueToCode(block, 'TIMES', repeats = Lua.valueToCode(block, 'TIMES', Lua.ORDER_NONE) || '0';
Blockly.Lua.ORDER_NONE) || '0';
} }
if (Blockly.utils.string.isNumber(repeats)) { if (stringUtils.isNumber(repeats)) {
repeats = parseInt(repeats, 10); repeats = parseInt(repeats, 10);
} else { } else {
repeats = 'math.floor(' + repeats + ')'; repeats = 'math.floor(' + repeats + ')';
} }
let branch = Blockly.Lua.statementToCode(block, 'DO'); let branch = Lua.statementToCode(block, 'DO');
branch = Blockly.Lua.addLoopTrap(branch, block); branch = Lua.addLoopTrap(branch, block);
branch = Blockly.Lua.addContinueLabel_(branch); branch = addContinueLabel(branch);
const loopVar = Blockly.Lua.nameDB_.getDistinctName( const loopVar = Lua.nameDB_.getDistinctName('count', NameType.VARIABLE);
'count', Blockly.VARIABLE_CATEGORY_NAME); const code =
const code = 'for ' + loopVar + ' = 1, ' + repeats + ' do\n' + 'for ' + loopVar + ' = 1, ' + repeats + ' do\n' + branch + 'end\n';
branch + 'end\n';
return code; return code;
}; };
Blockly.Lua['controls_repeat'] = Blockly.Lua['controls_repeat_ext']; Lua['controls_repeat'] = Lua['controls_repeat_ext'];
Blockly.Lua['controls_whileUntil'] = function(block) { Lua['controls_whileUntil'] = function(block) {
// Do while/until loop. // Do while/until loop.
const until = block.getFieldValue('MODE') === 'UNTIL'; const until = block.getFieldValue('MODE') === 'UNTIL';
let argument0 = Blockly.Lua.valueToCode(block, 'BOOL', let argument0 =
until ? Blockly.Lua.ORDER_UNARY : Lua.valueToCode(
Blockly.Lua.ORDER_NONE) || 'false'; block, 'BOOL', until ? Lua.ORDER_UNARY : Lua.ORDER_NONE) ||
let branch = Blockly.Lua.statementToCode(block, 'DO'); 'false';
branch = Blockly.Lua.addLoopTrap(branch, block); let branch = Lua.statementToCode(block, 'DO');
branch = Blockly.Lua.addContinueLabel_(branch); branch = Lua.addLoopTrap(branch, block);
branch = addContinueLabel(branch);
if (until) { if (until) {
argument0 = 'not ' + argument0; argument0 = 'not ' + argument0;
} }
return 'while ' + argument0 + ' do\n' + branch + 'end\n'; return 'while ' + argument0 + ' do\n' + branch + 'end\n';
}; };
Blockly.Lua['controls_for'] = function(block) { Lua['controls_for'] = function(block) {
// For loop. // For loop.
const variable0 = Blockly.Lua.nameDB_.getName( const variable0 =
block.getFieldValue('VAR'), Blockly.VARIABLE_CATEGORY_NAME); Lua.nameDB_.getName(block.getFieldValue('VAR'), NameType.VARIABLE);
const startVar = Blockly.Lua.valueToCode(block, 'FROM', const startVar = Lua.valueToCode(block, 'FROM', Lua.ORDER_NONE) || '0';
Blockly.Lua.ORDER_NONE) || '0'; const endVar = Lua.valueToCode(block, 'TO', Lua.ORDER_NONE) || '0';
const endVar = Blockly.Lua.valueToCode(block, 'TO', const increment = Lua.valueToCode(block, 'BY', Lua.ORDER_NONE) || '1';
Blockly.Lua.ORDER_NONE) || '0'; let branch = Lua.statementToCode(block, 'DO');
const increment = Blockly.Lua.valueToCode(block, 'BY', branch = Lua.addLoopTrap(branch, block);
Blockly.Lua.ORDER_NONE) || '1'; branch = addContinueLabel(branch);
let branch = Blockly.Lua.statementToCode(block, 'DO');
branch = Blockly.Lua.addLoopTrap(branch, block);
branch = Blockly.Lua.addContinueLabel_(branch);
let code = ''; let code = '';
let incValue; let incValue;
if (Blockly.utils.string.isNumber(startVar) && Blockly.utils.string.isNumber(endVar) && if (stringUtils.isNumber(startVar) && stringUtils.isNumber(endVar) &&
Blockly.utils.string.isNumber(increment)) { stringUtils.isNumber(increment)) {
// All arguments are simple numbers. // All arguments are simple numbers.
const up = Number(startVar) <= Number(endVar); const up = Number(startVar) <= Number(endVar);
const step = Math.abs(Number(increment)); const step = Math.abs(Number(increment));
@@ -111,64 +106,63 @@ Blockly.Lua['controls_for'] = function(block) {
code = ''; code = '';
// Determine loop direction at start, in case one of the bounds // Determine loop direction at start, in case one of the bounds
// changes during loop execution. // changes during loop execution.
incValue = Blockly.Lua.nameDB_.getDistinctName( incValue =
variable0 + '_inc', Blockly.VARIABLE_CATEGORY_NAME); Lua.nameDB_.getDistinctName(variable0 + '_inc', NameType.VARIABLE);
code += incValue + ' = '; code += incValue + ' = ';
if (Blockly.utils.string.isNumber(increment)) { if (stringUtils.isNumber(increment)) {
code += Math.abs(increment) + '\n'; code += Math.abs(increment) + '\n';
} else { } else {
code += 'math.abs(' + increment + ')\n'; code += 'math.abs(' + increment + ')\n';
} }
code += 'if (' + startVar + ') > (' + endVar + ') then\n'; code += 'if (' + startVar + ') > (' + endVar + ') then\n';
code += Blockly.Lua.INDENT + incValue + ' = -' + incValue + '\n'; code += Lua.INDENT + incValue + ' = -' + incValue + '\n';
code += 'end\n'; code += 'end\n';
} }
code += 'for ' + variable0 + ' = ' + startVar + ', ' + endVar + code +=
', ' + incValue; 'for ' + variable0 + ' = ' + startVar + ', ' + endVar + ', ' + incValue;
code += ' do\n' + branch + 'end\n'; code += ' do\n' + branch + 'end\n';
return code; return code;
}; };
Blockly.Lua['controls_forEach'] = function(block) { Lua['controls_forEach'] = function(block) {
// For each loop. // For each loop.
const variable0 = Blockly.Lua.nameDB_.getName( const variable0 =
block.getFieldValue('VAR'), Blockly.VARIABLE_CATEGORY_NAME); Lua.nameDB_.getName(block.getFieldValue('VAR'), NameType.VARIABLE);
const argument0 = Blockly.Lua.valueToCode(block, 'LIST', const argument0 = Lua.valueToCode(block, 'LIST', Lua.ORDER_NONE) || '{}';
Blockly.Lua.ORDER_NONE) || '{}'; let branch = Lua.statementToCode(block, 'DO');
let branch = Blockly.Lua.statementToCode(block, 'DO'); branch = Lua.addLoopTrap(branch, block);
branch = Blockly.Lua.addLoopTrap(branch, block); branch = addContinueLabel(branch);
branch = Blockly.Lua.addContinueLabel_(branch);
const code = 'for _, ' + variable0 + ' in ipairs(' + argument0 + ') do \n' + const code = 'for _, ' + variable0 + ' in ipairs(' + argument0 + ') do \n' +
branch + 'end\n'; branch + 'end\n';
return code; return code;
}; };
Blockly.Lua['controls_flow_statements'] = function(block) { Lua['controls_flow_statements'] = function(block) {
// Flow statements: continue, break. // Flow statements: continue, break.
let xfix = ''; let xfix = '';
if (Blockly.Lua.STATEMENT_PREFIX) { if (Lua.STATEMENT_PREFIX) {
// Automatic prefix insertion is switched off for this block. Add manually. // Automatic prefix insertion is switched off for this block. Add manually.
xfix += Blockly.Lua.injectId(Blockly.Lua.STATEMENT_PREFIX, block); xfix += Lua.injectId(Lua.STATEMENT_PREFIX, block);
} }
if (Blockly.Lua.STATEMENT_SUFFIX) { if (Lua.STATEMENT_SUFFIX) {
// Inject any statement suffix here since the regular one at the end // Inject any statement suffix here since the regular one at the end
// will not get executed if the break/continue is triggered. // will not get executed if the break/continue is triggered.
xfix += Blockly.Lua.injectId(Blockly.Lua.STATEMENT_SUFFIX, block); xfix += Lua.injectId(Lua.STATEMENT_SUFFIX, block);
} }
if (Blockly.Lua.STATEMENT_PREFIX) { if (Lua.STATEMENT_PREFIX) {
const loop = block.getSurroundLoop(); const loop = block.getSurroundLoop();
if (loop && !loop.suppressPrefixSuffix) { if (loop && !loop.suppressPrefixSuffix) {
// Inject loop's statement prefix here since the regular one at the end // Inject loop's statement prefix here since the regular one at the end
// of the loop will not get executed if 'continue' is triggered. // 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. // In the case of 'break', a prefix is needed due to the loop's suffix.
xfix += Blockly.Lua.injectId(Blockly.Lua.STATEMENT_PREFIX, loop); xfix += Lua.injectId(Lua.STATEMENT_PREFIX, loop);
} }
} }
switch (block.getFieldValue('FLOW')) { switch (block.getFieldValue('FLOW')) {
case 'BREAK': case 'BREAK':
return xfix + 'break\n'; return xfix + 'break\n';
case 'CONTINUE': case 'CONTINUE':
return xfix + Blockly.Lua.CONTINUE_STATEMENT; return xfix + CONTINUE_STATEMENT;
} }
throw Error('Unknown flow statement.'); throw Error('Unknown flow statement.');
}; };

View File

@@ -6,62 +6,57 @@
/** /**
* @fileoverview Generating Lua for math blocks. * @fileoverview Generating Lua for math blocks.
* @suppress {missingRequire}
*/ */
'use strict'; 'use strict';
goog.provide('Blockly.Lua.math'); goog.module('Blockly.Lua.math');
goog.require('Blockly.Lua'); const Lua = goog.require('Blockly.Lua');
const {NameType} = goog.require('Blockly.Names');
Blockly.Lua['math_number'] = function(block) { Lua['math_number'] = function(block) {
// Numeric value. // Numeric value.
const code = Number(block.getFieldValue('NUM')); const code = Number(block.getFieldValue('NUM'));
const order = code < 0 ? Blockly.Lua.ORDER_UNARY : const order = code < 0 ? Lua.ORDER_UNARY : Lua.ORDER_ATOMIC;
Blockly.Lua.ORDER_ATOMIC;
return [code, order]; return [code, order];
}; };
Blockly.Lua['math_arithmetic'] = function(block) { Lua['math_arithmetic'] = function(block) {
// Basic arithmetic operators, and power. // Basic arithmetic operators, and power.
const OPERATORS = { const OPERATORS = {
ADD: [' + ', Blockly.Lua.ORDER_ADDITIVE], ADD: [' + ', Lua.ORDER_ADDITIVE],
MINUS: [' - ', Blockly.Lua.ORDER_ADDITIVE], MINUS: [' - ', Lua.ORDER_ADDITIVE],
MULTIPLY: [' * ', Blockly.Lua.ORDER_MULTIPLICATIVE], MULTIPLY: [' * ', Lua.ORDER_MULTIPLICATIVE],
DIVIDE: [' / ', Blockly.Lua.ORDER_MULTIPLICATIVE], DIVIDE: [' / ', Lua.ORDER_MULTIPLICATIVE],
POWER: [' ^ ', Blockly.Lua.ORDER_EXPONENTIATION] POWER: [' ^ ', Lua.ORDER_EXPONENTIATION]
}; };
const tuple = OPERATORS[block.getFieldValue('OP')]; const tuple = OPERATORS[block.getFieldValue('OP')];
const operator = tuple[0]; const operator = tuple[0];
const order = tuple[1]; const order = tuple[1];
const argument0 = Blockly.Lua.valueToCode(block, 'A', order) || '0'; const argument0 = Lua.valueToCode(block, 'A', order) || '0';
const argument1 = Blockly.Lua.valueToCode(block, 'B', order) || '0'; const argument1 = Lua.valueToCode(block, 'B', order) || '0';
const code = argument0 + operator + argument1; const code = argument0 + operator + argument1;
return [code, order]; return [code, order];
}; };
Blockly.Lua['math_single'] = function(block) { Lua['math_single'] = function(block) {
// Math operators with single operand. // Math operators with single operand.
const operator = block.getFieldValue('OP'); const operator = block.getFieldValue('OP');
let arg; let arg;
if (operator === 'NEG') { if (operator === 'NEG') {
// Negation is a special case given its different operator precedence. // Negation is a special case given its different operator precedence.
arg = Blockly.Lua.valueToCode(block, 'NUM', arg = Lua.valueToCode(block, 'NUM', Lua.ORDER_UNARY) || '0';
Blockly.Lua.ORDER_UNARY) || '0'; return ['-' + arg, Lua.ORDER_UNARY];
return ['-' + arg, Blockly.Lua.ORDER_UNARY];
} }
if (operator === 'POW10') { if (operator === 'POW10') {
arg = Blockly.Lua.valueToCode(block, 'NUM', arg = Lua.valueToCode(block, 'NUM', Lua.ORDER_EXPONENTIATION) || '0';
Blockly.Lua.ORDER_EXPONENTIATION) || '0'; return ['10 ^ ' + arg, Lua.ORDER_EXPONENTIATION];
return ['10 ^ ' + arg, Blockly.Lua.ORDER_EXPONENTIATION];
} }
if (operator === 'ROUND') { if (operator === 'ROUND') {
arg = Blockly.Lua.valueToCode(block, 'NUM', arg = Lua.valueToCode(block, 'NUM', Lua.ORDER_ADDITIVE) || '0';
Blockly.Lua.ORDER_ADDITIVE) || '0';
} else { } else {
arg = Blockly.Lua.valueToCode(block, 'NUM', arg = Lua.valueToCode(block, 'NUM', Lua.ORDER_NONE) || '0';
Blockly.Lua.ORDER_NONE) || '0';
} }
let code; let code;
@@ -112,53 +107,47 @@ Blockly.Lua['math_single'] = function(block) {
default: default:
throw Error('Unknown math operator: ' + operator); throw Error('Unknown math operator: ' + operator);
} }
return [code, Blockly.Lua.ORDER_HIGH]; return [code, Lua.ORDER_HIGH];
}; };
Blockly.Lua['math_constant'] = function(block) { Lua['math_constant'] = function(block) {
// Constants: PI, E, the Golden Ratio, sqrt(2), 1/sqrt(2), INFINITY. // Constants: PI, E, the Golden Ratio, sqrt(2), 1/sqrt(2), INFINITY.
const CONSTANTS = { const CONSTANTS = {
PI: ['math.pi', Blockly.Lua.ORDER_HIGH], PI: ['math.pi', Lua.ORDER_HIGH],
E: ['math.exp(1)', Blockly.Lua.ORDER_HIGH], E: ['math.exp(1)', Lua.ORDER_HIGH],
GOLDEN_RATIO: ['(1 + math.sqrt(5)) / 2', Blockly.Lua.ORDER_MULTIPLICATIVE], GOLDEN_RATIO: ['(1 + math.sqrt(5)) / 2', Lua.ORDER_MULTIPLICATIVE],
SQRT2: ['math.sqrt(2)', Blockly.Lua.ORDER_HIGH], SQRT2: ['math.sqrt(2)', Lua.ORDER_HIGH],
SQRT1_2: ['math.sqrt(1 / 2)', Blockly.Lua.ORDER_HIGH], SQRT1_2: ['math.sqrt(1 / 2)', Lua.ORDER_HIGH],
INFINITY: ['math.huge', Blockly.Lua.ORDER_HIGH] INFINITY: ['math.huge', Lua.ORDER_HIGH]
}; };
return CONSTANTS[block.getFieldValue('CONSTANT')]; return CONSTANTS[block.getFieldValue('CONSTANT')];
}; };
Blockly.Lua['math_number_property'] = function(block) { Lua['math_number_property'] = function(block) {
// Check if a number is even, odd, prime, whole, positive, or negative // Check if a number is even, odd, prime, whole, positive, or negative
// or if it is divisible by certain number. Returns true or false. // or if it is divisible by certain number. Returns true or false.
const number_to_check = Blockly.Lua.valueToCode(block, 'NUMBER_TO_CHECK', const number_to_check =
Blockly.Lua.ORDER_MULTIPLICATIVE) || '0'; Lua.valueToCode(block, 'NUMBER_TO_CHECK', Lua.ORDER_MULTIPLICATIVE) ||
'0';
const dropdown_property = block.getFieldValue('PROPERTY'); const dropdown_property = block.getFieldValue('PROPERTY');
let code; let code;
if (dropdown_property === 'PRIME') { if (dropdown_property === 'PRIME') {
// Prime is a special case as it is not a one-liner test. // Prime is a special case as it is not a one-liner test.
const functionName = Blockly.Lua.provideFunction_( const functionName = Lua.provideFunction_('math_isPrime', [
'math_isPrime', 'function ' + Lua.FUNCTION_NAME_PLACEHOLDER_ + '(n)',
['function ' + Blockly.Lua.FUNCTION_NAME_PLACEHOLDER_ + '(n)', ' -- https://en.wikipedia.org/wiki/Primality_test#Naive_methods',
' -- https://en.wikipedia.org/wiki/Primality_test#Naive_methods', ' if n == 2 or n == 3 then', ' return true', ' end',
' if n == 2 or n == 3 then', ' -- False if n is NaN, negative, is 1, or not whole.',
' return true', ' -- And false if n is divisible by 2 or 3.',
' end', ' if not(n > 1) or n % 1 ~= 0 or n % 2 == 0 or n % 3 == 0 then',
' -- False if n is NaN, negative, is 1, or not whole.', ' return false', ' end',
' -- And false if n is divisible by 2 or 3.', ' -- Check all the numbers of form 6k +/- 1, up to sqrt(n).',
' if not(n > 1) or n % 1 ~= 0 or n % 2 == 0 or n % 3 == 0 then', ' for x = 6, math.sqrt(n) + 1.5, 6 do',
' return false', ' if n % (x - 1) == 0 or n % (x + 1) == 0 then', ' return false',
' end', ' end', ' end', ' return true', 'end'
' -- Check all the numbers of form 6k +/- 1, up to sqrt(n).', ]);
' for x = 6, math.sqrt(n) + 1.5, 6 do',
' if n % (x - 1) == 0 or n % (x + 1) == 0 then',
' return false',
' end',
' end',
' return true',
'end']);
code = functionName + '(' + number_to_check + ')'; code = functionName + '(' + number_to_check + ')';
return [code, Blockly.Lua.ORDER_HIGH]; return [code, Lua.ORDER_HIGH];
} }
switch (dropdown_property) { switch (dropdown_property) {
case 'EVEN': case 'EVEN':
@@ -177,12 +166,12 @@ Blockly.Lua['math_number_property'] = function(block) {
code = number_to_check + ' < 0'; code = number_to_check + ' < 0';
break; break;
case 'DIVISIBLE_BY': { case 'DIVISIBLE_BY': {
const divisor = Blockly.Lua.valueToCode(block, 'DIVISOR', const divisor =
Blockly.Lua.ORDER_MULTIPLICATIVE); Lua.valueToCode(block, 'DIVISOR', Lua.ORDER_MULTIPLICATIVE);
// If 'divisor' is some code that evals to 0, Lua will produce a nan. // If 'divisor' is some code that evals to 0, Lua will produce a nan.
// Let's produce nil if we can determine this at compile-time. // Let's produce nil if we can determine this at compile-time.
if (!divisor || divisor === '0') { if (!divisor || divisor === '0') {
return ['nil', Blockly.Lua.ORDER_ATOMIC]; return ['nil', Lua.ORDER_ATOMIC];
} }
// The normal trick to implement ?: with and/or doesn't work here: // The normal trick to implement ?: with and/or doesn't work here:
// divisor == 0 and nil or number_to_check % divisor == 0 // divisor == 0 and nil or number_to_check % divisor == 0
@@ -191,41 +180,35 @@ Blockly.Lua['math_number_property'] = function(block) {
break; break;
} }
} }
return [code, Blockly.Lua.ORDER_RELATIONAL]; return [code, Lua.ORDER_RELATIONAL];
}; };
Blockly.Lua['math_change'] = function(block) { Lua['math_change'] = function(block) {
// Add to a variable in place. // Add to a variable in place.
const argument0 = Blockly.Lua.valueToCode(block, 'DELTA', const argument0 = Lua.valueToCode(block, 'DELTA', Lua.ORDER_ADDITIVE) || '0';
Blockly.Lua.ORDER_ADDITIVE) || '0'; const varName =
const varName = Blockly.Lua.nameDB_.getName( Lua.nameDB_.getName(block.getFieldValue('VAR'), NameType.VARIABLE);
block.getFieldValue('VAR'), Blockly.VARIABLE_CATEGORY_NAME);
return varName + ' = ' + varName + ' + ' + argument0 + '\n'; return varName + ' = ' + varName + ' + ' + argument0 + '\n';
}; };
// Rounding functions have a single operand. // Rounding functions have a single operand.
Blockly.Lua['math_round'] = Blockly.Lua['math_single']; Lua['math_round'] = Lua['math_single'];
// Trigonometry functions have a single operand. // Trigonometry functions have a single operand.
Blockly.Lua['math_trig'] = Blockly.Lua['math_single']; Lua['math_trig'] = Lua['math_single'];
Blockly.Lua['math_on_list'] = function(block) { Lua['math_on_list'] = function(block) {
// Math functions for lists. // Math functions for lists.
const func = block.getFieldValue('OP'); const func = block.getFieldValue('OP');
const list = Blockly.Lua.valueToCode(block, 'LIST', const list = Lua.valueToCode(block, 'LIST', Lua.ORDER_NONE) || '{}';
Blockly.Lua.ORDER_NONE) || '{}';
let functionName; let functionName;
// Functions needed in more than one case. // Functions needed in more than one case.
function provideSum() { function provideSum() {
return Blockly.Lua.provideFunction_( return Lua.provideFunction_('math_sum', [
'math_sum', 'function ' + Lua.FUNCTION_NAME_PLACEHOLDER_ + '(t)',
['function ' + Blockly.Lua.FUNCTION_NAME_PLACEHOLDER_ + '(t)', ' local result = 0', ' for _, v in ipairs(t) do',
' local result = 0', ' result = result + v', ' end', ' return result', 'end'
' for _, v in ipairs(t) do', ]);
' result = result + v',
' end',
' return result',
'end']);
} }
switch (func) { switch (func) {
@@ -235,191 +218,151 @@ Blockly.Lua['math_on_list'] = function(block) {
case 'MIN': case 'MIN':
// Returns 0 for the empty list. // Returns 0 for the empty list.
functionName = Blockly.Lua.provideFunction_( functionName = Lua.provideFunction_('math_min', [
'math_min', 'function ' + Lua.FUNCTION_NAME_PLACEHOLDER_ + '(t)',
['function ' + Blockly.Lua.FUNCTION_NAME_PLACEHOLDER_ + '(t)', ' if #t == 0 then', ' return 0', ' end',
' if #t == 0 then', ' local result = math.huge', ' for _, v in ipairs(t) do',
' return 0', ' if v < result then', ' result = v', ' end', ' end',
' end', ' return result', 'end'
' local result = math.huge', ]);
' for _, v in ipairs(t) do',
' if v < result then',
' result = v',
' end',
' end',
' return result',
'end']);
break; break;
case 'AVERAGE': case 'AVERAGE':
// Returns 0 for the empty list. // Returns 0 for the empty list.
functionName = Blockly.Lua.provideFunction_( functionName = Lua.provideFunction_('math_average', [
'math_average', 'function ' + Lua.FUNCTION_NAME_PLACEHOLDER_ + '(t)',
['function ' + Blockly.Lua.FUNCTION_NAME_PLACEHOLDER_ + '(t)', ' if #t == 0 then', ' return 0', ' end',
' if #t == 0 then', ' return ' + provideSum() + '(t) / #t', 'end'
' return 0', ]);
' end',
' return ' + provideSum() + '(t) / #t',
'end']);
break; break;
case 'MAX': case 'MAX':
// Returns 0 for the empty list. // Returns 0 for the empty list.
functionName = Blockly.Lua.provideFunction_( functionName = Lua.provideFunction_('math_max', [
'math_max', 'function ' + Lua.FUNCTION_NAME_PLACEHOLDER_ + '(t)',
['function ' + Blockly.Lua.FUNCTION_NAME_PLACEHOLDER_ + '(t)', ' if #t == 0 then', ' return 0', ' end',
' if #t == 0 then', ' local result = -math.huge', ' for _, v in ipairs(t) do',
' return 0', ' if v > result then', ' result = v', ' end', ' end',
' end', ' return result', 'end'
' local result = -math.huge', ]);
' for _, v in ipairs(t) do',
' if v > result then',
' result = v',
' end',
' end',
' return result',
'end']);
break; break;
case 'MEDIAN': case 'MEDIAN':
functionName = Blockly.Lua.provideFunction_( functionName = Lua.provideFunction_(
'math_median', 'math_median',
// This operation excludes non-numbers. // This operation excludes non-numbers.
['function ' + Blockly.Lua.FUNCTION_NAME_PLACEHOLDER_ + '(t)', [
' -- Source: http://lua-users.org/wiki/SimpleStats', 'function ' + Lua.FUNCTION_NAME_PLACEHOLDER_ + '(t)',
' if #t == 0 then', ' -- Source: http://lua-users.org/wiki/SimpleStats',
' return 0', ' if #t == 0 then', ' return 0', ' end', ' local temp={}',
' end', ' for _, v in ipairs(t) do', ' if type(v) == "number" then',
' local temp={}', ' table.insert(temp, v)', ' end', ' end',
' for _, v in ipairs(t) do', ' table.sort(temp)', ' if #temp % 2 == 0 then',
' if type(v) == "number" then', ' return (temp[#temp/2] + temp[(#temp/2)+1]) / 2', ' else',
' table.insert(temp, v)', ' return temp[math.ceil(#temp/2)]', ' end', 'end'
' end', ]);
' end',
' table.sort(temp)',
' if #temp % 2 == 0 then',
' return (temp[#temp/2] + temp[(#temp/2)+1]) / 2',
' else',
' return temp[math.ceil(#temp/2)]',
' end',
'end']);
break; break;
case 'MODE': case 'MODE':
functionName = Blockly.Lua.provideFunction_( functionName = Lua.provideFunction_(
'math_modes', 'math_modes',
// As a list of numbers can contain more than one mode, // As a list of numbers can contain more than one mode,
// the returned result is provided as an array. // the returned result is provided as an array.
// The Lua version includes non-numbers. // The Lua version includes non-numbers.
['function ' + Blockly.Lua.FUNCTION_NAME_PLACEHOLDER_ + '(t)', [
' -- Source: http://lua-users.org/wiki/SimpleStats', 'function ' + Lua.FUNCTION_NAME_PLACEHOLDER_ + '(t)',
' local counts={}', ' -- Source: http://lua-users.org/wiki/SimpleStats',
' for _, v in ipairs(t) do', ' local counts={}',
' if counts[v] == nil then', ' for _, v in ipairs(t) do',
' counts[v] = 1', ' if counts[v] == nil then',
' else', ' counts[v] = 1',
' counts[v] = counts[v] + 1', ' else',
' end', ' counts[v] = counts[v] + 1',
' end', ' end',
' local biggestCount = 0', ' end',
' for _, v in pairs(counts) do', ' local biggestCount = 0',
' if v > biggestCount then', ' for _, v in pairs(counts) do',
' biggestCount = v', ' if v > biggestCount then',
' end', ' biggestCount = v',
' end', ' end',
' local temp={}', ' end',
' for k, v in pairs(counts) do', ' local temp={}',
' if v == biggestCount then', ' for k, v in pairs(counts) do',
' table.insert(temp, k)', ' if v == biggestCount then',
' end', ' table.insert(temp, k)',
' end', ' end',
' return temp', ' end',
'end']); ' return temp',
'end'
]);
break; break;
case 'STD_DEV': case 'STD_DEV':
functionName = Blockly.Lua.provideFunction_( functionName = Lua.provideFunction_('math_standard_deviation', [
'math_standard_deviation', 'function ' + Lua.FUNCTION_NAME_PLACEHOLDER_ + '(t)', ' local m',
['function ' + Blockly.Lua.FUNCTION_NAME_PLACEHOLDER_ + '(t)', ' local vm', ' local total = 0', ' local count = 0',
' local m', ' local result', ' m = #t == 0 and 0 or ' + provideSum() + '(t) / #t',
' local vm', ' for _, v in ipairs(t) do', ' if type(v) == \'number\' then',
' local total = 0', ' vm = v - m', ' total = total + (vm * vm)',
' local count = 0', ' count = count + 1', ' end', ' end',
' local result', ' result = math.sqrt(total / (count-1))', ' return result', 'end'
' m = #t == 0 and 0 or ' + provideSum() + '(t) / #t', ]);
' for _, v in ipairs(t) do',
" if type(v) == 'number' then",
' vm = v - m',
' total = total + (vm * vm)',
' count = count + 1',
' end',
' end',
' result = math.sqrt(total / (count-1))',
' return result',
'end']);
break; break;
case 'RANDOM': case 'RANDOM':
functionName = Blockly.Lua.provideFunction_( functionName = Lua.provideFunction_('math_random_list', [
'math_random_list', 'function ' + Lua.FUNCTION_NAME_PLACEHOLDER_ + '(t)',
['function ' + Blockly.Lua.FUNCTION_NAME_PLACEHOLDER_ + '(t)', ' if #t == 0 then', ' return nil', ' end',
' if #t == 0 then', ' return t[math.random(#t)]', 'end'
' return nil', ]);
' end',
' return t[math.random(#t)]',
'end']);
break; break;
default: default:
throw Error('Unknown operator: ' + func); throw Error('Unknown operator: ' + func);
} }
return [functionName + '(' + list + ')', Blockly.Lua.ORDER_HIGH]; return [functionName + '(' + list + ')', Lua.ORDER_HIGH];
}; };
Blockly.Lua['math_modulo'] = function(block) { Lua['math_modulo'] = function(block) {
// Remainder computation. // Remainder computation.
const argument0 = Blockly.Lua.valueToCode(block, 'DIVIDEND', const argument0 =
Blockly.Lua.ORDER_MULTIPLICATIVE) || '0'; Lua.valueToCode(block, 'DIVIDEND', Lua.ORDER_MULTIPLICATIVE) || '0';
const argument1 = Blockly.Lua.valueToCode(block, 'DIVISOR', const argument1 =
Blockly.Lua.ORDER_MULTIPLICATIVE) || '0'; Lua.valueToCode(block, 'DIVISOR', Lua.ORDER_MULTIPLICATIVE) || '0';
const code = argument0 + ' % ' + argument1; const code = argument0 + ' % ' + argument1;
return [code, Blockly.Lua.ORDER_MULTIPLICATIVE]; return [code, Lua.ORDER_MULTIPLICATIVE];
}; };
Blockly.Lua['math_constrain'] = function(block) { Lua['math_constrain'] = function(block) {
// Constrain a number between two limits. // Constrain a number between two limits.
const argument0 = Blockly.Lua.valueToCode(block, 'VALUE', const argument0 = Lua.valueToCode(block, 'VALUE', Lua.ORDER_NONE) || '0';
Blockly.Lua.ORDER_NONE) || '0'; const argument1 =
const argument1 = Blockly.Lua.valueToCode(block, 'LOW', Lua.valueToCode(block, 'LOW', Lua.ORDER_NONE) || '-math.huge';
Blockly.Lua.ORDER_NONE) || '-math.huge'; const argument2 =
const argument2 = Blockly.Lua.valueToCode(block, 'HIGH', Lua.valueToCode(block, 'HIGH', Lua.ORDER_NONE) || 'math.huge';
Blockly.Lua.ORDER_NONE) || 'math.huge';
const code = 'math.min(math.max(' + argument0 + ', ' + argument1 + '), ' + const code = 'math.min(math.max(' + argument0 + ', ' + argument1 + '), ' +
argument2 + ')'; argument2 + ')';
return [code, Blockly.Lua.ORDER_HIGH]; return [code, Lua.ORDER_HIGH];
}; };
Blockly.Lua['math_random_int'] = function(block) { Lua['math_random_int'] = function(block) {
// Random integer between [X] and [Y]. // Random integer between [X] and [Y].
const argument0 = Blockly.Lua.valueToCode(block, 'FROM', const argument0 = Lua.valueToCode(block, 'FROM', Lua.ORDER_NONE) || '0';
Blockly.Lua.ORDER_NONE) || '0'; const argument1 = Lua.valueToCode(block, 'TO', Lua.ORDER_NONE) || '0';
const argument1 = Blockly.Lua.valueToCode(block, 'TO',
Blockly.Lua.ORDER_NONE) || '0';
const code = 'math.random(' + argument0 + ', ' + argument1 + ')'; const code = 'math.random(' + argument0 + ', ' + argument1 + ')';
return [code, Blockly.Lua.ORDER_HIGH]; return [code, Lua.ORDER_HIGH];
}; };
Blockly.Lua['math_random_float'] = function(block) { Lua['math_random_float'] = function(block) {
// Random fraction between 0 and 1. // Random fraction between 0 and 1.
return ['math.random()', Blockly.Lua.ORDER_HIGH]; return ['math.random()', Lua.ORDER_HIGH];
}; };
Blockly.Lua['math_atan2'] = function(block) { Lua['math_atan2'] = function(block) {
// Arctangent of point (X, Y) in degrees from -180 to 180. // Arctangent of point (X, Y) in degrees from -180 to 180.
const argument0 = Blockly.Lua.valueToCode(block, 'X', const argument0 = Lua.valueToCode(block, 'X', Lua.ORDER_NONE) || '0';
Blockly.Lua.ORDER_NONE) || '0'; const argument1 = Lua.valueToCode(block, 'Y', Lua.ORDER_NONE) || '0';
const argument1 = Blockly.Lua.valueToCode(block, 'Y', return [
Blockly.Lua.ORDER_NONE) || '0'; 'math.deg(math.atan2(' + argument1 + ', ' + argument0 + '))', Lua.ORDER_HIGH
return ['math.deg(math.atan2(' + argument1 + ', ' + argument0 + '))', ];
Blockly.Lua.ORDER_HIGH];
}; };

View File

@@ -6,107 +6,100 @@
/** /**
* @fileoverview Generating Lua for procedure blocks. * @fileoverview Generating Lua for procedure blocks.
* @suppress {missingRequire}
*/ */
'use strict'; 'use strict';
goog.provide('Blockly.Lua.procedures'); goog.module('Blockly.Lua.procedures');
goog.require('Blockly.Lua'); const Lua = goog.require('Blockly.Lua');
const {NameType} = goog.require('Blockly.Names');
Blockly.Lua['procedures_defreturn'] = function(block) { Lua['procedures_defreturn'] = function(block) {
// Define a procedure with a return value. // Define a procedure with a return value.
const funcName = Blockly.Lua.nameDB_.getName( const funcName =
block.getFieldValue('NAME'), Blockly.PROCEDURE_CATEGORY_NAME); Lua.nameDB_.getName(block.getFieldValue('NAME'), NameType.PROCEDURE);
let xfix1 = ''; let xfix1 = '';
if (Blockly.Lua.STATEMENT_PREFIX) { if (Lua.STATEMENT_PREFIX) {
xfix1 += Blockly.Lua.injectId(Blockly.Lua.STATEMENT_PREFIX, block); xfix1 += Lua.injectId(Lua.STATEMENT_PREFIX, block);
} }
if (Blockly.Lua.STATEMENT_SUFFIX) { if (Lua.STATEMENT_SUFFIX) {
xfix1 += Blockly.Lua.injectId(Blockly.Lua.STATEMENT_SUFFIX, block); xfix1 += Lua.injectId(Lua.STATEMENT_SUFFIX, block);
} }
if (xfix1) { if (xfix1) {
xfix1 = Blockly.Lua.prefixLines(xfix1, Blockly.Lua.INDENT); xfix1 = Lua.prefixLines(xfix1, Lua.INDENT);
} }
let loopTrap = ''; let loopTrap = '';
if (Blockly.Lua.INFINITE_LOOP_TRAP) { if (Lua.INFINITE_LOOP_TRAP) {
loopTrap = Blockly.Lua.prefixLines( loopTrap = Lua.prefixLines(
Blockly.Lua.injectId(Blockly.Lua.INFINITE_LOOP_TRAP, block), Lua.injectId(Lua.INFINITE_LOOP_TRAP, block), Lua.INDENT);
Blockly.Lua.INDENT);
} }
let branch = Blockly.Lua.statementToCode(block, 'STACK'); let branch = Lua.statementToCode(block, 'STACK');
let returnValue = Blockly.Lua.valueToCode(block, 'RETURN', let returnValue = Lua.valueToCode(block, 'RETURN', Lua.ORDER_NONE) || '';
Blockly.Lua.ORDER_NONE) || '';
let xfix2 = ''; let xfix2 = '';
if (branch && returnValue) { if (branch && returnValue) {
// After executing the function body, revisit this block for the return. // After executing the function body, revisit this block for the return.
xfix2 = xfix1; xfix2 = xfix1;
} }
if (returnValue) { if (returnValue) {
returnValue = Blockly.Lua.INDENT + 'return ' + returnValue + '\n'; returnValue = Lua.INDENT + 'return ' + returnValue + '\n';
} else if (!branch) { } else if (!branch) {
branch = ''; branch = '';
} }
const args = []; const args = [];
const variables = block.getVars(); const variables = block.getVars();
for (let i = 0; i < variables.length; i++) { for (let i = 0; i < variables.length; i++) {
args[i] = Blockly.Lua.nameDB_.getName(variables[i], args[i] = Lua.nameDB_.getName(variables[i], NameType.VARIABLE);
Blockly.VARIABLE_CATEGORY_NAME);
} }
let code = 'function ' + funcName + '(' + args.join(', ') + ')\n' + let code = 'function ' + funcName + '(' + args.join(', ') + ')\n' + xfix1 +
xfix1 + loopTrap + branch + xfix2 + returnValue + 'end\n'; loopTrap + branch + xfix2 + returnValue + 'end\n';
code = Blockly.Lua.scrub_(block, code); code = Lua.scrub_(block, code);
// Add % so as not to collide with helper functions in definitions list. // Add % so as not to collide with helper functions in definitions list.
Blockly.Lua.definitions_['%' + funcName] = code; Lua.definitions_['%' + funcName] = code;
return null; return null;
}; };
// Defining a procedure without a return value uses the same generator as // Defining a procedure without a return value uses the same generator as
// a procedure with a return value. // a procedure with a return value.
Blockly.Lua['procedures_defnoreturn'] = Lua['procedures_defnoreturn'] = Lua['procedures_defreturn'];
Blockly.Lua['procedures_defreturn'];
Blockly.Lua['procedures_callreturn'] = function(block) { Lua['procedures_callreturn'] = function(block) {
// Call a procedure with a return value. // Call a procedure with a return value.
const funcName = Blockly.Lua.nameDB_.getName( const funcName =
block.getFieldValue('NAME'), Blockly.PROCEDURE_CATEGORY_NAME); Lua.nameDB_.getName(block.getFieldValue('NAME'), NameType.PROCEDURE);
const args = []; const args = [];
const variables = block.getVars(); const variables = block.getVars();
for (let i = 0; i < variables.length; i++) { for (let i = 0; i < variables.length; i++) {
args[i] = Blockly.Lua.valueToCode(block, 'ARG' + i, args[i] = Lua.valueToCode(block, 'ARG' + i, Lua.ORDER_NONE) || 'nil';
Blockly.Lua.ORDER_NONE) || 'nil';
} }
const code = funcName + '(' + args.join(', ') + ')'; const code = funcName + '(' + args.join(', ') + ')';
return [code, Blockly.Lua.ORDER_HIGH]; return [code, Lua.ORDER_HIGH];
}; };
Blockly.Lua['procedures_callnoreturn'] = function(block) { Lua['procedures_callnoreturn'] = function(block) {
// Call a procedure with no return value. // Call a procedure with no return value.
// Generated code is for a function call as a statement is the same as a // 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. // function call as a value, with the addition of line ending.
const tuple = Blockly.Lua['procedures_callreturn'](block); const tuple = Lua['procedures_callreturn'](block);
return tuple[0] + '\n'; return tuple[0] + '\n';
}; };
Blockly.Lua['procedures_ifreturn'] = function(block) { Lua['procedures_ifreturn'] = function(block) {
// Conditionally return value from a procedure. // Conditionally return value from a procedure.
const condition = Blockly.Lua.valueToCode(block, 'CONDITION', const condition =
Blockly.Lua.ORDER_NONE) || 'false'; Lua.valueToCode(block, 'CONDITION', Lua.ORDER_NONE) || 'false';
let code = 'if ' + condition + ' then\n'; let code = 'if ' + condition + ' then\n';
if (Blockly.Lua.STATEMENT_SUFFIX) { if (Lua.STATEMENT_SUFFIX) {
// Inject any statement suffix here since the regular one at the end // Inject any statement suffix here since the regular one at the end
// will not get executed if the return is triggered. // will not get executed if the return is triggered.
code += Blockly.Lua.prefixLines( code +=
Blockly.Lua.injectId(Blockly.Lua.STATEMENT_SUFFIX, block), Lua.prefixLines(Lua.injectId(Lua.STATEMENT_SUFFIX, block), Lua.INDENT);
Blockly.Lua.INDENT);
} }
if (block.hasReturnValue_) { if (block.hasReturnValue_) {
const value = Blockly.Lua.valueToCode(block, 'VALUE', const value = Lua.valueToCode(block, 'VALUE', Lua.ORDER_NONE) || 'nil';
Blockly.Lua.ORDER_NONE) || 'nil'; code += Lua.INDENT + 'return ' + value + '\n';
code += Blockly.Lua.INDENT + 'return ' + value + '\n';
} else { } else {
code += Blockly.Lua.INDENT + 'return\n'; code += Lua.INDENT + 'return\n';
} }
code += 'end\n'; code += 'end\n';
return code; return code;

View File

@@ -6,132 +6,113 @@
/** /**
* @fileoverview Generating Lua for text blocks. * @fileoverview Generating Lua for text blocks.
* @suppress {missingRequire}
*/ */
'use strict'; 'use strict';
goog.provide('Blockly.Lua.texts'); goog.module('Blockly.Lua.texts');
goog.require('Blockly.Lua'); const Lua = goog.require('Blockly.Lua');
const {NameType} = goog.require('Blockly.Names');
Blockly.Lua['text'] = function(block) { Lua['text'] = function(block) {
// Text value. // Text value.
const code = Blockly.Lua.quote_(block.getFieldValue('TEXT')); const code = Lua.quote_(block.getFieldValue('TEXT'));
return [code, Blockly.Lua.ORDER_ATOMIC]; return [code, Lua.ORDER_ATOMIC];
}; };
Blockly.Lua['text_multiline'] = function(block) { Lua['text_multiline'] = function(block) {
// Text value. // Text value.
const code = Blockly.Lua.multiline_quote_(block.getFieldValue('TEXT')); const code = Lua.multiline_quote_(block.getFieldValue('TEXT'));
const order = code.indexOf('..') !== -1 ? Blockly.Lua.ORDER_CONCATENATION : const order =
Blockly.Lua.ORDER_ATOMIC; code.indexOf('..') !== -1 ? Lua.ORDER_CONCATENATION : Lua.ORDER_ATOMIC;
return [code, order]; return [code, order];
}; };
Blockly.Lua['text_join'] = function(block) { Lua['text_join'] = function(block) {
// Create a string made up of any number of elements of any type. // Create a string made up of any number of elements of any type.
if (block.itemCount_ === 0) { if (block.itemCount_ === 0) {
return ['\'\'', Blockly.Lua.ORDER_ATOMIC]; return ['\'\'', Lua.ORDER_ATOMIC];
} else if (block.itemCount_ === 1) { } else if (block.itemCount_ === 1) {
const element = Blockly.Lua.valueToCode(block, 'ADD0', const element = Lua.valueToCode(block, 'ADD0', Lua.ORDER_NONE) || '\'\'';
Blockly.Lua.ORDER_NONE) || '\'\'';
const code = 'tostring(' + element + ')'; const code = 'tostring(' + element + ')';
return [code, Blockly.Lua.ORDER_HIGH]; return [code, Lua.ORDER_HIGH];
} else if (block.itemCount_ === 2) { } else if (block.itemCount_ === 2) {
const element0 = Blockly.Lua.valueToCode(block, 'ADD0', const element0 =
Blockly.Lua.ORDER_CONCATENATION) || '\'\''; Lua.valueToCode(block, 'ADD0', Lua.ORDER_CONCATENATION) || '\'\'';
const element1 = Blockly.Lua.valueToCode(block, 'ADD1', const element1 =
Blockly.Lua.ORDER_CONCATENATION) || '\'\''; Lua.valueToCode(block, 'ADD1', Lua.ORDER_CONCATENATION) || '\'\'';
const code = element0 + ' .. ' + element1; const code = element0 + ' .. ' + element1;
return [code, Blockly.Lua.ORDER_CONCATENATION]; return [code, Lua.ORDER_CONCATENATION];
} else { } else {
const elements = []; const elements = [];
for (let i = 0; i < block.itemCount_; i++) { for (let i = 0; i < block.itemCount_; i++) {
elements[i] = Blockly.Lua.valueToCode(block, 'ADD' + i, elements[i] = Lua.valueToCode(block, 'ADD' + i, Lua.ORDER_NONE) || '\'\'';
Blockly.Lua.ORDER_NONE) || '\'\'';
} }
const code = 'table.concat({' + elements.join(', ') + '})'; const code = 'table.concat({' + elements.join(', ') + '})';
return [code, Blockly.Lua.ORDER_HIGH]; return [code, Lua.ORDER_HIGH];
} }
}; };
Blockly.Lua['text_append'] = function(block) { Lua['text_append'] = function(block) {
// Append to a variable in place. // Append to a variable in place.
const varName = Blockly.Lua.nameDB_.getName( const varName =
block.getFieldValue('VAR'), Blockly.VARIABLE_CATEGORY_NAME); Lua.nameDB_.getName(block.getFieldValue('VAR'), NameType.VARIABLE);
const value = Blockly.Lua.valueToCode(block, 'TEXT', const value =
Blockly.Lua.ORDER_CONCATENATION) || '\'\''; Lua.valueToCode(block, 'TEXT', Lua.ORDER_CONCATENATION) || '\'\'';
return varName + ' = ' + varName + ' .. ' + value + '\n'; return varName + ' = ' + varName + ' .. ' + value + '\n';
}; };
Blockly.Lua['text_length'] = function(block) { Lua['text_length'] = function(block) {
// String or array length. // String or array length.
const text = Blockly.Lua.valueToCode(block, 'VALUE', const text = Lua.valueToCode(block, 'VALUE', Lua.ORDER_UNARY) || '\'\'';
Blockly.Lua.ORDER_UNARY) || '\'\''; return ['#' + text, Lua.ORDER_UNARY];
return ['#' + text, Blockly.Lua.ORDER_UNARY];
}; };
Blockly.Lua['text_isEmpty'] = function(block) { Lua['text_isEmpty'] = function(block) {
// Is the string null or array empty? // Is the string null or array empty?
const text = Blockly.Lua.valueToCode(block, 'VALUE', const text = Lua.valueToCode(block, 'VALUE', Lua.ORDER_UNARY) || '\'\'';
Blockly.Lua.ORDER_UNARY) || '\'\''; return ['#' + text + ' == 0', Lua.ORDER_RELATIONAL];
return ['#' + text + ' == 0', Blockly.Lua.ORDER_RELATIONAL];
}; };
Blockly.Lua['text_indexOf'] = function(block) { Lua['text_indexOf'] = function(block) {
// Search the text for a substring. // Search the text for a substring.
const substring = Blockly.Lua.valueToCode(block, 'FIND', const substring = Lua.valueToCode(block, 'FIND', Lua.ORDER_NONE) || '\'\'';
Blockly.Lua.ORDER_NONE) || '\'\''; const text = Lua.valueToCode(block, 'VALUE', Lua.ORDER_NONE) || '\'\'';
const text = Blockly.Lua.valueToCode(block, 'VALUE',
Blockly.Lua.ORDER_NONE) || '\'\'';
let functionName; let functionName;
if (block.getFieldValue('END') === 'FIRST') { if (block.getFieldValue('END') === 'FIRST') {
functionName = Blockly.Lua.provideFunction_( functionName = Lua.provideFunction_('firstIndexOf', [
'firstIndexOf', 'function ' + Lua.FUNCTION_NAME_PLACEHOLDER_ + '(str, substr) ',
['function ' + Blockly.Lua.FUNCTION_NAME_PLACEHOLDER_ + ' local i = string.find(str, substr, 1, true)', ' if i == nil then',
'(str, substr) ', ' return 0', ' else', ' return i', ' end', 'end'
' local i = string.find(str, substr, 1, true)', ]);
' if i == nil then',
' return 0',
' else',
' return i',
' end',
'end']);
} else { } else {
functionName = Blockly.Lua.provideFunction_( functionName = Lua.provideFunction_('lastIndexOf', [
'lastIndexOf', 'function ' + Lua.FUNCTION_NAME_PLACEHOLDER_ + '(str, substr)',
['function ' + Blockly.Lua.FUNCTION_NAME_PLACEHOLDER_ + ' local i = string.find(string.reverse(str), ' +
'(str, substr)', 'string.reverse(substr), 1, true)',
' local i = string.find(string.reverse(str), ' + ' if i then', ' return #str + 2 - i - #substr', ' end', ' return 0',
'string.reverse(substr), 1, true)', 'end'
' if i then', ]);
' return #str + 2 - i - #substr',
' end',
' return 0',
'end']);
} }
const code = functionName + '(' + text + ', ' + substring + ')'; const code = functionName + '(' + text + ', ' + substring + ')';
return [code, Blockly.Lua.ORDER_HIGH]; return [code, Lua.ORDER_HIGH];
}; };
Blockly.Lua['text_charAt'] = function(block) { Lua['text_charAt'] = function(block) {
// Get letter at index. // Get letter at index.
// Note: Until January 2013 this block did not have the WHERE input. // Note: Until January 2013 this block did not have the WHERE input.
const where = block.getFieldValue('WHERE') || 'FROM_START'; const where = block.getFieldValue('WHERE') || 'FROM_START';
const atOrder = (where === 'FROM_END') ? Blockly.Lua.ORDER_UNARY : const atOrder = (where === 'FROM_END') ? Lua.ORDER_UNARY : Lua.ORDER_NONE;
Blockly.Lua.ORDER_NONE; const at = Lua.valueToCode(block, 'AT', atOrder) || '1';
const at = Blockly.Lua.valueToCode(block, 'AT', atOrder) || '1'; const text = Lua.valueToCode(block, 'VALUE', Lua.ORDER_NONE) || '\'\'';
const text = Blockly.Lua.valueToCode(block, 'VALUE',
Blockly.Lua.ORDER_NONE) || '\'\'';
let code; let code;
if (where === 'RANDOM') { if (where === 'RANDOM') {
const functionName = Blockly.Lua.provideFunction_( const functionName = Lua.provideFunction_('text_random_letter', [
'text_random_letter', 'function ' + Lua.FUNCTION_NAME_PLACEHOLDER_ + '(str)',
['function ' + Blockly.Lua.FUNCTION_NAME_PLACEHOLDER_ + '(str)', ' local index = math.random(string.len(str))',
' local index = math.random(string.len(str))', ' return string.sub(str, index, index)', 'end'
' return string.sub(str, index, index)', ]);
'end']);
code = functionName + '(' + text + ')'; code = functionName + '(' + text + ')';
} else { } else {
let start; let start;
@@ -152,28 +133,24 @@ Blockly.Lua['text_charAt'] = function(block) {
code = 'string.sub(' + text + ', ' + start + ', ' + start + ')'; code = 'string.sub(' + text + ', ' + start + ', ' + start + ')';
} else { } else {
// use function to avoid reevaluation // use function to avoid reevaluation
const functionName = Blockly.Lua.provideFunction_( const functionName = Lua.provideFunction_('text_char_at', [
'text_char_at', 'function ' + Lua.FUNCTION_NAME_PLACEHOLDER_ + '(str, index)',
['function ' + Blockly.Lua.FUNCTION_NAME_PLACEHOLDER_ + ' return string.sub(str, index, index)', 'end'
'(str, index)', ]);
' return string.sub(str, index, index)',
'end']);
code = functionName + '(' + text + ', ' + start + ')'; code = functionName + '(' + text + ', ' + start + ')';
} }
} }
return [code, Blockly.Lua.ORDER_HIGH]; return [code, Lua.ORDER_HIGH];
}; };
Blockly.Lua['text_getSubstring'] = function(block) { Lua['text_getSubstring'] = function(block) {
// Get substring. // Get substring.
const text = Blockly.Lua.valueToCode(block, 'STRING', const text = Lua.valueToCode(block, 'STRING', Lua.ORDER_NONE) || '\'\'';
Blockly.Lua.ORDER_NONE) || '\'\'';
// Get start index. // Get start index.
const where1 = block.getFieldValue('WHERE1'); const where1 = block.getFieldValue('WHERE1');
const at1Order = (where1 === 'FROM_END') ? Blockly.Lua.ORDER_UNARY : const at1Order = (where1 === 'FROM_END') ? Lua.ORDER_UNARY : Lua.ORDER_NONE;
Blockly.Lua.ORDER_NONE; const at1 = Lua.valueToCode(block, 'AT1', at1Order) || '1';
const at1 = Blockly.Lua.valueToCode(block, 'AT1', at1Order) || '1';
let start; let start;
if (where1 === 'FIRST') { if (where1 === 'FIRST') {
start = 1; start = 1;
@@ -187,9 +164,8 @@ Blockly.Lua['text_getSubstring'] = function(block) {
// Get end index. // Get end index.
const where2 = block.getFieldValue('WHERE2'); const where2 = block.getFieldValue('WHERE2');
const at2Order = (where2 === 'FROM_END') ? Blockly.Lua.ORDER_UNARY : const at2Order = (where2 === 'FROM_END') ? Lua.ORDER_UNARY : Lua.ORDER_NONE;
Blockly.Lua.ORDER_NONE; const at2 = Lua.valueToCode(block, 'AT2', at2Order) || '1';
const at2 = Blockly.Lua.valueToCode(block, 'AT2', at2Order) || '1';
let end; let end;
if (where2 === 'LAST') { if (where2 === 'LAST') {
end = -1; end = -1;
@@ -201,161 +177,134 @@ Blockly.Lua['text_getSubstring'] = function(block) {
throw Error('Unhandled option (text_getSubstring)'); throw Error('Unhandled option (text_getSubstring)');
} }
const code = 'string.sub(' + text + ', ' + start + ', ' + end + ')'; const code = 'string.sub(' + text + ', ' + start + ', ' + end + ')';
return [code, Blockly.Lua.ORDER_HIGH]; return [code, Lua.ORDER_HIGH];
}; };
Blockly.Lua['text_changeCase'] = function(block) { Lua['text_changeCase'] = function(block) {
// Change capitalization. // Change capitalization.
const operator = block.getFieldValue('CASE'); const operator = block.getFieldValue('CASE');
const text = Blockly.Lua.valueToCode(block, 'TEXT', const text = Lua.valueToCode(block, 'TEXT', Lua.ORDER_NONE) || '\'\'';
Blockly.Lua.ORDER_NONE) || '\'\'';
let functionName; let functionName;
if (operator === 'UPPERCASE') { if (operator === 'UPPERCASE') {
functionName = 'string.upper'; functionName = 'string.upper';
} else if (operator === 'LOWERCASE') { } else if (operator === 'LOWERCASE') {
functionName = 'string.lower'; functionName = 'string.lower';
} else if (operator === 'TITLECASE') { } else if (operator === 'TITLECASE') {
functionName = Blockly.Lua.provideFunction_( functionName = Lua.provideFunction_(
'text_titlecase', 'text_titlecase',
// There are shorter versions at // There are shorter versions at
// http://lua-users.org/wiki/SciteTitleCase // http://lua-users.org/wiki/SciteTitleCase
// that do not preserve whitespace. // that do not preserve whitespace.
['function ' + Blockly.Lua.FUNCTION_NAME_PLACEHOLDER_ + '(str)', [
' local buf = {}', 'function ' + Lua.FUNCTION_NAME_PLACEHOLDER_ + '(str)',
' local inWord = false', ' local buf = {}', ' local inWord = false', ' for i = 1, #str do',
' for i = 1, #str do', ' local c = string.sub(str, i, i)', ' if inWord then',
' local c = string.sub(str, i, i)', ' table.insert(buf, string.lower(c))',
' if inWord then', ' if string.find(c, "%s") then', ' inWord = false',
' table.insert(buf, string.lower(c))', ' end', ' else', ' table.insert(buf, string.upper(c))',
' if string.find(c, "%s") then', ' inWord = true', ' end', ' end',
' inWord = false', ' return table.concat(buf)', 'end'
' end', ]);
' else',
' table.insert(buf, string.upper(c))',
' inWord = true',
' end',
' end',
' return table.concat(buf)',
'end']);
} }
const code = functionName + '(' + text + ')'; const code = functionName + '(' + text + ')';
return [code, Blockly.Lua.ORDER_HIGH]; return [code, Lua.ORDER_HIGH];
}; };
Blockly.Lua['text_trim'] = function(block) { Lua['text_trim'] = function(block) {
// Trim spaces. // Trim spaces.
const OPERATORS = { const OPERATORS = {LEFT: '^%s*(,-)', RIGHT: '(.-)%s*$', BOTH: '^%s*(.-)%s*$'};
LEFT: '^%s*(,-)',
RIGHT: '(.-)%s*$',
BOTH: '^%s*(.-)%s*$'
};
const operator = OPERATORS[block.getFieldValue('MODE')]; const operator = OPERATORS[block.getFieldValue('MODE')];
const text = Blockly.Lua.valueToCode(block, 'TEXT', const text = Lua.valueToCode(block, 'TEXT', Lua.ORDER_NONE) || '\'\'';
Blockly.Lua.ORDER_NONE) || '\'\'';
const code = 'string.gsub(' + text + ', "' + operator + '", "%1")'; const code = 'string.gsub(' + text + ', "' + operator + '", "%1")';
return [code, Blockly.Lua.ORDER_HIGH]; return [code, Lua.ORDER_HIGH];
}; };
Blockly.Lua['text_print'] = function(block) { Lua['text_print'] = function(block) {
// Print statement. // Print statement.
const msg = Blockly.Lua.valueToCode(block, 'TEXT', const msg = Lua.valueToCode(block, 'TEXT', Lua.ORDER_NONE) || '\'\'';
Blockly.Lua.ORDER_NONE) || '\'\'';
return 'print(' + msg + ')\n'; return 'print(' + msg + ')\n';
}; };
Blockly.Lua['text_prompt_ext'] = function(block) { Lua['text_prompt_ext'] = function(block) {
// Prompt function. // Prompt function.
let msg; let msg;
if (block.getField('TEXT')) { if (block.getField('TEXT')) {
// Internal message. // Internal message.
msg = Blockly.Lua.quote_(block.getFieldValue('TEXT')); msg = Lua.quote_(block.getFieldValue('TEXT'));
} else { } else {
// External message. // External message.
msg = Blockly.Lua.valueToCode(block, 'TEXT', msg = Lua.valueToCode(block, 'TEXT', Lua.ORDER_NONE) || '\'\'';
Blockly.Lua.ORDER_NONE) || '\'\'';
} }
const functionName = Blockly.Lua.provideFunction_( const functionName = Lua.provideFunction_('text_prompt', [
'text_prompt', 'function ' + Lua.FUNCTION_NAME_PLACEHOLDER_ + '(msg)', ' io.write(msg)',
['function ' + Blockly.Lua.FUNCTION_NAME_PLACEHOLDER_ + '(msg)', ' io.flush()', ' return io.read()', 'end'
' io.write(msg)', ]);
' io.flush()',
' return io.read()',
'end']);
let code = functionName + '(' + msg + ')'; let code = functionName + '(' + msg + ')';
const toNumber = block.getFieldValue('TYPE') === 'NUMBER'; const toNumber = block.getFieldValue('TYPE') === 'NUMBER';
if (toNumber) { if (toNumber) {
code = 'tonumber(' + code + ', 10)'; code = 'tonumber(' + code + ', 10)';
} }
return [code, Blockly.Lua.ORDER_HIGH]; return [code, Lua.ORDER_HIGH];
}; };
Blockly.Lua['text_prompt'] = Blockly.Lua['text_prompt_ext']; Lua['text_prompt'] = Lua['text_prompt_ext'];
Blockly.Lua['text_count'] = function(block) { Lua['text_count'] = function(block) {
const text = Blockly.Lua.valueToCode(block, 'TEXT', const text = Lua.valueToCode(block, 'TEXT', Lua.ORDER_NONE) || '\'\'';
Blockly.Lua.ORDER_NONE) || '\'\''; const sub = Lua.valueToCode(block, 'SUB', Lua.ORDER_NONE) || '\'\'';
const sub = Blockly.Lua.valueToCode(block, 'SUB', const functionName = Lua.provideFunction_('text_count', [
Blockly.Lua.ORDER_NONE) || '\'\''; 'function ' + Lua.FUNCTION_NAME_PLACEHOLDER_ + '(haystack, needle)',
const functionName = Blockly.Lua.provideFunction_( ' if #needle == 0 then',
'text_count', ' return #haystack + 1',
['function ' + Blockly.Lua.FUNCTION_NAME_PLACEHOLDER_ ' end',
+ '(haystack, needle)', ' local i = 1',
' if #needle == 0 then', ' local count = 0',
' return #haystack + 1', ' while true do',
' end', ' i = string.find(haystack, needle, i, true)',
' local i = 1', ' if i == nil then',
' local count = 0', ' break',
' while true do', ' end',
' i = string.find(haystack, needle, i, true)', ' count = count + 1',
' if i == nil then', ' i = i + #needle',
' break', ' end',
' end', ' return count',
' count = count + 1', 'end',
' i = i + #needle', ]);
' end',
' return count',
'end',
]);
const code = functionName + '(' + text + ', ' + sub + ')'; const code = functionName + '(' + text + ', ' + sub + ')';
return [code, Blockly.Lua.ORDER_HIGH]; return [code, Lua.ORDER_HIGH];
}; };
Blockly.Lua['text_replace'] = function(block) { Lua['text_replace'] = function(block) {
const text = Blockly.Lua.valueToCode(block, 'TEXT', const text = Lua.valueToCode(block, 'TEXT', Lua.ORDER_NONE) || '\'\'';
Blockly.Lua.ORDER_NONE) || '\'\''; const from = Lua.valueToCode(block, 'FROM', Lua.ORDER_NONE) || '\'\'';
const from = Blockly.Lua.valueToCode(block, 'FROM', const to = Lua.valueToCode(block, 'TO', Lua.ORDER_NONE) || '\'\'';
Blockly.Lua.ORDER_NONE) || '\'\''; const functionName = Lua.provideFunction_('text_replace', [
const to = Blockly.Lua.valueToCode(block, 'TO', 'function ' + Lua.FUNCTION_NAME_PLACEHOLDER_ +
Blockly.Lua.ORDER_NONE) || '\'\''; '(haystack, needle, replacement)',
const functionName = Blockly.Lua.provideFunction_( ' local buf = {}',
'text_replace', ' local i = 1',
['function ' + Blockly.Lua.FUNCTION_NAME_PLACEHOLDER_ ' while i <= #haystack do',
+ '(haystack, needle, replacement)', ' if string.sub(haystack, i, i + #needle - 1) == needle then',
' local buf = {}', ' for j = 1, #replacement do',
' local i = 1', ' table.insert(buf, string.sub(replacement, j, j))',
' while i <= #haystack do', ' end',
' if string.sub(haystack, i, i + #needle - 1) == needle then', ' i = i + #needle',
' for j = 1, #replacement do', ' else',
' table.insert(buf, string.sub(replacement, j, j))', ' table.insert(buf, string.sub(haystack, i, i))',
' end', ' i = i + 1',
' i = i + #needle', ' end',
' else', ' end',
' table.insert(buf, string.sub(haystack, i, i))', ' return table.concat(buf)',
' i = i + 1', 'end',
' end', ]);
' end',
' return table.concat(buf)',
'end',
]);
const code = functionName + '(' + text + ', ' + from + ', ' + to + ')'; const code = functionName + '(' + text + ', ' + from + ', ' + to + ')';
return [code, Blockly.Lua.ORDER_HIGH]; return [code, Lua.ORDER_HIGH];
}; };
Blockly.Lua['text_reverse'] = function(block) { Lua['text_reverse'] = function(block) {
const text = Blockly.Lua.valueToCode(block, 'TEXT', const text = Lua.valueToCode(block, 'TEXT', Lua.ORDER_NONE) || '\'\'';
Blockly.Lua.ORDER_NONE) || '\'\'';
const code = 'string.reverse(' + text + ')'; const code = 'string.reverse(' + text + ')';
return [code, Blockly.Lua.ORDER_HIGH]; return [code, Lua.ORDER_HIGH];
}; };

View File

@@ -6,27 +6,26 @@
/** /**
* @fileoverview Generating Lua for variable blocks. * @fileoverview Generating Lua for variable blocks.
* @suppress {missingRequire}
*/ */
'use strict'; 'use strict';
goog.provide('Blockly.Lua.variables'); goog.module('Blockly.Lua.variables');
goog.require('Blockly.Lua'); const Lua = goog.require('Blockly.Lua');
const {NameType} = goog.require('Blockly.Names');
Blockly.Lua['variables_get'] = function(block) { Lua['variables_get'] = function(block) {
// Variable getter. // Variable getter.
const code = Blockly.Lua.nameDB_.getName(block.getFieldValue('VAR'), const code =
Blockly.VARIABLE_CATEGORY_NAME); Lua.nameDB_.getName(block.getFieldValue('VAR'), NameType.VARIABLE);
return [code, Blockly.Lua.ORDER_ATOMIC]; return [code, Lua.ORDER_ATOMIC];
}; };
Blockly.Lua['variables_set'] = function(block) { Lua['variables_set'] = function(block) {
// Variable setter. // Variable setter.
const argument0 = Blockly.Lua.valueToCode(block, 'VALUE', const argument0 = Lua.valueToCode(block, 'VALUE', Lua.ORDER_NONE) || '0';
Blockly.Lua.ORDER_NONE) || '0'; const varName =
const varName = Blockly.Lua.nameDB_.getName( Lua.nameDB_.getName(block.getFieldValue('VAR'), NameType.VARIABLE);
block.getFieldValue('VAR'), Blockly.VARIABLE_CATEGORY_NAME);
return varName + ' = ' + argument0 + '\n'; return varName + ' = ' + argument0 + '\n';
}; };

View File

@@ -6,16 +6,16 @@
/** /**
* @fileoverview Generating Lua for dynamic variable blocks. * @fileoverview Generating Lua for dynamic variable blocks.
* @suppress {extraRequire}
*/ */
'use strict'; 'use strict';
goog.provide('Blockly.Lua.variablesDynamic'); goog.module('Blockly.Lua.variablesDynamic');
goog.require('Blockly.Lua'); const Lua = goog.require('Blockly.Lua');
/** @suppress {extraRequire} */
goog.require('Blockly.Lua.variables'); goog.require('Blockly.Lua.variables');
// Lua is dynamically typed. // Lua is dynamically typed.
Blockly.Lua['variables_get_dynamic'] = Blockly.Lua['variables_get']; Lua['variables_get_dynamic'] = Lua['variables_get'];
Blockly.Lua['variables_set_dynamic'] = Blockly.Lua['variables_set']; Lua['variables_set_dynamic'] = Lua['variables_set'];

View File

@@ -289,15 +289,15 @@ goog.addDependency('../../generators/javascript/variables.js', ['Blockly.JavaScr
goog.addDependency('../../generators/javascript/variables_dynamic.js', ['Blockly.JavaScript.variablesDynamic'], ['Blockly.JavaScript', 'Blockly.JavaScript.variables'], {'lang': 'es6', 'module': 'goog'}); goog.addDependency('../../generators/javascript/variables_dynamic.js', ['Blockly.JavaScript.variablesDynamic'], ['Blockly.JavaScript', 'Blockly.JavaScript.variables'], {'lang': 'es6', 'module': 'goog'});
goog.addDependency('../../generators/lua.js', ['Blockly.Lua'], ['Blockly.Generator', 'Blockly.Names', 'Blockly.inputTypes', 'Blockly.utils.object', 'Blockly.utils.string'], {'lang': 'es6'}); goog.addDependency('../../generators/lua.js', ['Blockly.Lua'], ['Blockly.Generator', 'Blockly.Names', 'Blockly.inputTypes', 'Blockly.utils.object', 'Blockly.utils.string'], {'lang': 'es6'});
goog.addDependency('../../generators/lua/all.js', ['Blockly.Lua.all'], ['Blockly.Lua.colour', 'Blockly.Lua.lists', 'Blockly.Lua.logic', 'Blockly.Lua.loops', 'Blockly.Lua.math', 'Blockly.Lua.procedures', 'Blockly.Lua.texts', 'Blockly.Lua.variables', 'Blockly.Lua.variablesDynamic'], {'module': 'goog'}); goog.addDependency('../../generators/lua/all.js', ['Blockly.Lua.all'], ['Blockly.Lua.colour', 'Blockly.Lua.lists', 'Blockly.Lua.logic', 'Blockly.Lua.loops', 'Blockly.Lua.math', 'Blockly.Lua.procedures', 'Blockly.Lua.texts', 'Blockly.Lua.variables', 'Blockly.Lua.variablesDynamic'], {'module': 'goog'});
goog.addDependency('../../generators/lua/colour.js', ['Blockly.Lua.colour'], ['Blockly.Lua'], {'lang': 'es6'}); goog.addDependency('../../generators/lua/colour.js', ['Blockly.Lua.colour'], ['Blockly.Lua'], {'lang': 'es6', 'module': 'goog'});
goog.addDependency('../../generators/lua/lists.js', ['Blockly.Lua.lists'], ['Blockly.Lua'], {'lang': 'es6'}); goog.addDependency('../../generators/lua/lists.js', ['Blockly.Lua.lists'], ['Blockly.Lua', 'Blockly.Names'], {'lang': 'es6', 'module': 'goog'});
goog.addDependency('../../generators/lua/logic.js', ['Blockly.Lua.logic'], ['Blockly.Lua'], {'lang': 'es6'}); goog.addDependency('../../generators/lua/logic.js', ['Blockly.Lua.logic'], ['Blockly.Lua'], {'lang': 'es6', 'module': 'goog'});
goog.addDependency('../../generators/lua/loops.js', ['Blockly.Lua.loops'], ['Blockly.Lua', 'Blockly.utils.string'], {'lang': 'es6'}); goog.addDependency('../../generators/lua/loops.js', ['Blockly.Lua.loops'], ['Blockly.Lua', 'Blockly.Names', 'Blockly.utils.string'], {'lang': 'es6', 'module': 'goog'});
goog.addDependency('../../generators/lua/math.js', ['Blockly.Lua.math'], ['Blockly.Lua'], {'lang': 'es6'}); goog.addDependency('../../generators/lua/math.js', ['Blockly.Lua.math'], ['Blockly.Lua', 'Blockly.Names'], {'lang': 'es6', 'module': 'goog'});
goog.addDependency('../../generators/lua/procedures.js', ['Blockly.Lua.procedures'], ['Blockly.Lua'], {'lang': 'es6'}); goog.addDependency('../../generators/lua/procedures.js', ['Blockly.Lua.procedures'], ['Blockly.Lua', 'Blockly.Names'], {'lang': 'es6', 'module': 'goog'});
goog.addDependency('../../generators/lua/text.js', ['Blockly.Lua.texts'], ['Blockly.Lua'], {'lang': 'es6'}); goog.addDependency('../../generators/lua/text.js', ['Blockly.Lua.texts'], ['Blockly.Lua', 'Blockly.Names'], {'lang': 'es6', 'module': 'goog'});
goog.addDependency('../../generators/lua/variables.js', ['Blockly.Lua.variables'], ['Blockly.Lua'], {'lang': 'es6'}); goog.addDependency('../../generators/lua/variables.js', ['Blockly.Lua.variables'], ['Blockly.Lua', 'Blockly.Names'], {'lang': 'es6', 'module': 'goog'});
goog.addDependency('../../generators/lua/variables_dynamic.js', ['Blockly.Lua.variablesDynamic'], ['Blockly.Lua', 'Blockly.Lua.variables']); goog.addDependency('../../generators/lua/variables_dynamic.js', ['Blockly.Lua.variablesDynamic'], ['Blockly.Lua', 'Blockly.Lua.variables'], {'lang': 'es6', 'module': 'goog'});
goog.addDependency('../../generators/php.js', ['Blockly.PHP'], ['Blockly.Generator', 'Blockly.Names', 'Blockly.inputTypes', 'Blockly.utils.object', 'Blockly.utils.string'], {'lang': 'es6'}); goog.addDependency('../../generators/php.js', ['Blockly.PHP'], ['Blockly.Generator', 'Blockly.Names', 'Blockly.inputTypes', 'Blockly.utils.object', 'Blockly.utils.string'], {'lang': 'es6'});
goog.addDependency('../../generators/php/all.js', ['Blockly.PHP.all'], ['Blockly.PHP.colour', 'Blockly.PHP.lists', 'Blockly.PHP.logic', 'Blockly.PHP.loops', 'Blockly.PHP.math', 'Blockly.PHP.procedures', 'Blockly.PHP.texts', 'Blockly.PHP.variables', 'Blockly.PHP.variablesDynamic'], {'module': 'goog'}); goog.addDependency('../../generators/php/all.js', ['Blockly.PHP.all'], ['Blockly.PHP.colour', 'Blockly.PHP.lists', 'Blockly.PHP.logic', 'Blockly.PHP.loops', 'Blockly.PHP.math', 'Blockly.PHP.procedures', 'Blockly.PHP.texts', 'Blockly.PHP.variables', 'Blockly.PHP.variablesDynamic'], {'module': 'goog'});
goog.addDependency('../../generators/php/colour.js', ['Blockly.PHP.colour'], ['Blockly.PHP'], {'lang': 'es6'}); goog.addDependency('../../generators/php/colour.js', ['Blockly.PHP.colour'], ['Blockly.PHP'], {'lang': 'es6'});