refactor(generators): Migrate Lua generators to TypeScript (#7654)

* refactor(generators): Migrate lua_generator.js to TypeScript

* refactor(generators): Migrate generators/lua/* to TypeScript

* fix(generators): Fix type errors in generator functions

* refactor(generators): Migrate generators/lua.js to TypeScript

* chore(generator): Format

* chore(generators): JSDoc and formatting tweaks for PR #7654

---------

Co-authored-by: Christopher Allen <cpcallen+git@google.com>
This commit is contained in:
Blake Thomas Williams
2023-11-20 12:46:32 -06:00
committed by GitHub
parent 149f95ecb4
commit dc61e487b4
12 changed files with 813 additions and 472 deletions

View File

@@ -5,9 +5,8 @@
*/ */
/** /**
* @fileoverview Complete helper functions for generating Lua for * @file Complete helper functions for generating Lua for
* blocks. This is the entrypoint for lua_compressed.js. * blocks. This is the entrypoint for lua_compressed.js.
* @suppress {extraRequire}
*/ */
// Former goog.module ID: Blockly.Lua.all // Former goog.module ID: Blockly.Lua.all
@@ -27,13 +26,21 @@ export * from './lua/lua_generator.js';
/** /**
* Lua code generator instance. * Lua code generator instance.
* @type {!LuaGenerator}
*/ */
export const luaGenerator = new LuaGenerator(); export const luaGenerator = new LuaGenerator();
// Install per-block-type generator functions: // Install per-block-type generator functions:
Object.assign( const generators: typeof luaGenerator.forBlock = {
luaGenerator.forBlock, ...colour,
colour, lists, logic, loops, math, procedures, ...lists,
text, variables, variablesDynamic ...logic,
); ...loops,
...math,
...procedures,
...text,
...variables,
...variablesDynamic,
};
for (const name in generators) {
luaGenerator.forBlock[name] = generators[name];
}

View File

@@ -5,46 +5,64 @@
*/ */
/** /**
* @fileoverview Generating Lua for colour blocks. * @file Generating Lua for colour blocks.
*/ */
// Former goog.module ID: Blockly.Lua.colour // Former goog.module ID: Blockly.Lua.colour
import type {Block} from '../../core/block.js';
import type {LuaGenerator} from './lua_generator.js';
import {Order} from './lua_generator.js'; import {Order} from './lua_generator.js';
export function colour_picker(
export function colour_picker(block, generator) { block: Block,
generator: LuaGenerator,
): [string, Order] {
// Colour picker. // Colour picker.
const code = generator.quote_(block.getFieldValue('COLOUR')); const code = generator.quote_(block.getFieldValue('COLOUR'));
return [code, Order.ATOMIC]; return [code, Order.ATOMIC];
}; }
export function colour_random(block, generator) { export function colour_random(
block: Block,
generator: LuaGenerator,
): [string, Order] {
// 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, Order.HIGH]; return [code, Order.HIGH];
}; }
export function colour_rgb(block, generator) { export function colour_rgb(
block: Block,
generator: LuaGenerator,
): [string, Order] {
// Compose a colour from RGB components expressed as percentages. // Compose a colour from RGB components expressed as percentages.
const functionName = generator.provideFunction_('colour_rgb', ` const functionName = generator.provideFunction_(
'colour_rgb',
`
function ${generator.FUNCTION_NAME_PLACEHOLDER_}(r, g, b) function ${generator.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) return string.format("#%02x%02x%02x", r, g, b)
end end
`); `,
);
const r = generator.valueToCode(block, 'RED', Order.NONE) || 0; const r = generator.valueToCode(block, 'RED', Order.NONE) || 0;
const g = generator.valueToCode(block, 'GREEN', Order.NONE) || 0; const g = generator.valueToCode(block, 'GREEN', Order.NONE) || 0;
const b = generator.valueToCode(block, 'BLUE', Order.NONE) || 0; const b = generator.valueToCode(block, 'BLUE', Order.NONE) || 0;
const code = functionName + '(' + r + ', ' + g + ', ' + b + ')'; const code = functionName + '(' + r + ', ' + g + ', ' + b + ')';
return [code, Order.HIGH]; return [code, Order.HIGH];
}; }
export function colour_blend(block, generator) { export function colour_blend(
block: Block,
generator: LuaGenerator,
): [string, Order] {
// Blend two colours together. // Blend two colours together.
const functionName = generator.provideFunction_('colour_blend', ` const functionName = generator.provideFunction_(
'colour_blend',
`
function ${generator.FUNCTION_NAME_PLACEHOLDER_}(colour1, colour2, ratio) function ${generator.FUNCTION_NAME_PLACEHOLDER_}(colour1, colour2, ratio)
local r1 = tonumber(string.sub(colour1, 2, 3), 16) local r1 = tonumber(string.sub(colour1, 2, 3), 16)
local r2 = tonumber(string.sub(colour2, 2, 3), 16) local r2 = tonumber(string.sub(colour2, 2, 3), 16)
@@ -58,13 +76,14 @@ function ${generator.FUNCTION_NAME_PLACEHOLDER_}(colour1, colour2, ratio)
local b = math.floor(b1 * (1 - ratio) + b2 * ratio + .5) local b = math.floor(b1 * (1 - ratio) + b2 * ratio + .5)
return string.format("#%02x%02x%02x", r, g, b) return string.format("#%02x%02x%02x", r, g, b)
end end
`); `,
);
const colour1 = const colour1 =
generator.valueToCode(block, 'COLOUR1', Order.NONE) || "'#000000'"; generator.valueToCode(block, 'COLOUR1', Order.NONE) || "'#000000'";
const colour2 = const colour2 =
generator.valueToCode(block, 'COLOUR2', Order.NONE) || "'#000000'"; generator.valueToCode(block, 'COLOUR2', Order.NONE) || "'#000000'";
const ratio = generator.valueToCode(block, 'RATIO', Order.NONE) || 0; const ratio = generator.valueToCode(block, 'RATIO', Order.NONE) || 0;
const code = const code =
functionName + '(' + colour1 + ', ' + colour2 + ', ' + ratio + ')'; functionName + '(' + colour1 + ', ' + colour2 + ', ' + ratio + ')';
return [code, Order.HIGH]; return [code, Order.HIGH];
}; }

View File

@@ -5,34 +5,48 @@
*/ */
/** /**
* @fileoverview Generating Lua for list blocks. * @file Generating Lua for list blocks.
*/ */
// Former goog.module ID: Blockly.Lua.lists // Former goog.module ID: Blockly.Lua.lists
import type {Block} from '../../core/block.js';
import type {CreateWithBlock} from '../../blocks/lists.js';
import type {LuaGenerator} from './lua_generator.js';
import {NameType} from '../../core/names.js'; import {NameType} from '../../core/names.js';
import {Order} from './lua_generator.js'; import {Order} from './lua_generator.js';
export function lists_create_empty(
export function lists_create_empty(block, generator) { block: Block,
generator: LuaGenerator,
): [string, Order] {
// Create an empty list. // Create an empty list.
return ['{}', Order.HIGH]; return ['{}', Order.HIGH];
}; }
export function lists_create_with(block, generator) { export function lists_create_with(
block: Block,
generator: LuaGenerator,
): [string, Order] {
const createWithBlock = block as CreateWithBlock;
// 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(createWithBlock.itemCount_);
for (let i = 0; i < block.itemCount_; i++) { for (let i = 0; i < createWithBlock.itemCount_; i++) {
elements[i] = elements[i] =
generator.valueToCode(block, 'ADD' + i, Order.NONE) || 'None'; generator.valueToCode(createWithBlock, 'ADD' + i, Order.NONE) || 'None';
} }
const code = '{' + elements.join(', ') + '}'; const code = '{' + elements.join(', ') + '}';
return [code, Order.HIGH]; return [code, Order.HIGH];
}; }
export function lists_repeat(block, generator) { export function lists_repeat(
block: Block,
generator: LuaGenerator,
): [string, Order] {
// Create a list with one element repeated. // Create a list with one element repeated.
const functionName = generator.provideFunction_('create_list_repeated', ` const functionName = generator.provideFunction_(
'create_list_repeated',
`
function ${generator.FUNCTION_NAME_PLACEHOLDER_}(item, count) function ${generator.FUNCTION_NAME_PLACEHOLDER_}(item, count)
local t = {} local t = {}
for i = 1, count do for i = 1, count do
@@ -40,33 +54,45 @@ function ${generator.FUNCTION_NAME_PLACEHOLDER_}(item, count)
end end
return t return t
end end
`); `,
);
const element = generator.valueToCode(block, 'ITEM', Order.NONE) || 'None'; const element = generator.valueToCode(block, 'ITEM', Order.NONE) || 'None';
const repeatCount = generator.valueToCode(block, 'NUM', Order.NONE) || '0'; const repeatCount = generator.valueToCode(block, 'NUM', Order.NONE) || '0';
const code = functionName + '(' + element + ', ' + repeatCount + ')'; const code = functionName + '(' + element + ', ' + repeatCount + ')';
return [code, Order.HIGH]; return [code, Order.HIGH];
}; }
export function lists_length(block, generator) { export function lists_length(
block: Block,
generator: LuaGenerator,
): [string, Order] {
// String or array length. // String or array length.
const list = generator.valueToCode(block, 'VALUE', Order.UNARY) || '{}'; const list = generator.valueToCode(block, 'VALUE', Order.UNARY) || '{}';
return ['#' + list, Order.UNARY]; return ['#' + list, Order.UNARY];
}; }
export function lists_isEmpty(block, generator) { export function lists_isEmpty(
block: Block,
generator: LuaGenerator,
): [string, Order] {
// Is the string null or array empty? // Is the string null or array empty?
const list = generator.valueToCode(block, 'VALUE', Order.UNARY) || '{}'; const list = generator.valueToCode(block, 'VALUE', Order.UNARY) || '{}';
const code = '#' + list + ' == 0'; const code = '#' + list + ' == 0';
return [code, Order.RELATIONAL]; return [code, Order.RELATIONAL];
}; }
export function lists_indexOf(block, generator) { export function lists_indexOf(
block: Block,
generator: LuaGenerator,
): [string, Order] {
// Find an item in the list. // Find an item in the list.
const item = generator.valueToCode(block, 'FIND', Order.NONE) || "''"; const item = generator.valueToCode(block, 'FIND', Order.NONE) || "''";
const list = generator.valueToCode(block, 'VALUE', Order.NONE) || '{}'; const list = generator.valueToCode(block, 'VALUE', Order.NONE) || '{}';
let functionName; let functionName;
if (block.getFieldValue('END') === 'FIRST') { if (block.getFieldValue('END') === 'FIRST') {
functionName = generator.provideFunction_('first_index', ` functionName = generator.provideFunction_(
'first_index',
`
function ${generator.FUNCTION_NAME_PLACEHOLDER_}(t, elem) function ${generator.FUNCTION_NAME_PLACEHOLDER_}(t, elem)
for k, v in ipairs(t) do for k, v in ipairs(t) do
if v == elem then if v == elem then
@@ -75,9 +101,12 @@ function ${generator.FUNCTION_NAME_PLACEHOLDER_}(t, elem)
end end
return 0 return 0
end end
`); `,
);
} else { } else {
functionName = generator.provideFunction_('last_index', ` functionName = generator.provideFunction_(
'last_index',
`
function ${generator.FUNCTION_NAME_PLACEHOLDER_}(t, elem) function ${generator.FUNCTION_NAME_PLACEHOLDER_}(t, elem)
for i = #t, 1, -1 do for i = #t, 1, -1 do
if t[i] == elem then if t[i] == elem then
@@ -86,20 +115,26 @@ function ${generator.FUNCTION_NAME_PLACEHOLDER_}(t, elem)
end end
return 0 return 0
end end
`); `,
);
} }
const code = functionName + '(' + list + ', ' + item + ')'; const code = functionName + '(' + list + ', ' + item + ')';
return [code, Order.HIGH]; return [code, Order.HIGH];
}; }
/** /**
* Returns an expression calculating the index into a list. * Returns an expression calculating the index into a list.
* @param {string} listName Name of the list, used to calculate length. *
* @param {string} where The method of indexing, selected by dropdown in Blockly * @param listName Name of the list, used to calculate length.
* @param {string=} opt_at The optional offset when indexing from start/end. * @param where The method of indexing, selected by dropdown in Blockly
* @return {string|undefined} Index expression. * @param opt_at The optional offset when indexing from start/end.
* @returns Index expression.
*/ */
const getListIndex = function(listName, where, opt_at) { const getListIndex = function (
listName: string,
where: string,
opt_at: string,
): string {
if (where === 'FIRST') { if (where === 'FIRST') {
return '1'; return '1';
} else if (where === 'FROM_END') { } else if (where === 'FROM_END') {
@@ -113,7 +148,10 @@ const getListIndex = function(listName, where, opt_at) {
} }
}; };
export function lists_getIndex(block, generator) { export function lists_getIndex(
block: Block,
generator: LuaGenerator,
): [string, Order] | string {
// 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';
@@ -122,19 +160,30 @@ export function lists_getIndex(block, generator) {
// 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.
if ((where === 'LAST' || where === 'FROM_END' || where === 'RANDOM') && if (
!list.match(/^\w+$/)) { (where === 'LAST' || where === 'FROM_END' || where === 'RANDOM') &&
!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.
if (mode === 'REMOVE') { if (mode === 'REMOVE') {
// We can use multiple statements. // We can use multiple statements.
const atOrder = const atOrder = where === 'FROM_END' ? Order.ADDITIVE : Order.NONE;
(where === 'FROM_END') ? Order.ADDITIVE : Order.NONE;
let at = generator.valueToCode(block, 'AT', atOrder) || '1'; let at = generator.valueToCode(block, 'AT', atOrder) || '1';
const listVar = const listVar = generator.nameDB_!.getDistinctName(
generator.nameDB_.getDistinctName('tmp_list', NameType.VARIABLE); 'tmp_list',
NameType.VARIABLE,
);
at = getListIndex(listVar, where, at); at = getListIndex(listVar, where, at);
const code = listVar + ' = ' + list + '\n' + const code =
'table.remove(' + listVar + ', ' + at + ')\n'; listVar +
' = ' +
list +
'\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.
@@ -142,41 +191,49 @@ export function lists_getIndex(block, generator) {
let functionName; let functionName;
if (mode === 'GET') { if (mode === 'GET') {
functionName = generator.provideFunction_( functionName = generator.provideFunction_(
'list_get_' + where.toLowerCase(), [ 'list_get_' + where.toLowerCase(),
'function ' + generator.FUNCTION_NAME_PLACEHOLDER_ + '(t' + [
'function ' +
generator.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') + ']',
' return t[' + getListIndex('t', where, 'at') + ']', 'end' 'end',
]); ],
} else { // `mode` === 'GET_REMOVE' );
functionName = } else {
generator.provideFunction_( // `mode` === 'GET_REMOVE'
'list_remove_' + where.toLowerCase(), [ functionName = generator.provideFunction_(
'function ' + generator.FUNCTION_NAME_PLACEHOLDER_ + '(t' + 'list_remove_' + where.toLowerCase(),
// The value for 'FROM_END' and'FROM_START' depends on `at` so [
// we add it as a parameter. 'function ' +
((where === 'FROM_END' || where === 'FROM_START') ? ', at)' : generator.FUNCTION_NAME_PLACEHOLDER_ +
')'), '(t' +
' return table.remove(t, ' + getListIndex('t', where, 'at') + // The value for 'FROM_END' and'FROM_START' depends on `at` so
')', // we add it as a parameter.
'end' (where === 'FROM_END' || where === 'FROM_START' ? ', at)' : ')'),
]); ' return table.remove(t, ' + getListIndex('t', where, 'at') + ')',
'end',
],
);
} }
const code = functionName + '(' + list + const code =
// The value for 'FROM_END' and 'FROM_START' depends on `at` so we functionName +
// pass it. '(' +
((where === 'FROM_END' || where === 'FROM_START') ? ', ' + at : '') + list +
')'; // The value for 'FROM_END' and 'FROM_START' depends on `at` so we
// pass it.
(where === 'FROM_END' || where === 'FROM_START' ? ', ' + at : '') +
')';
return [code, Order.HIGH]; return [code, 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 =
Order.ADDITIVE : mode === 'GET' && where === 'FROM_END' ? Order.ADDITIVE : Order.NONE;
Order.NONE;
let at = generator.valueToCode(block, 'AT', atOrder) || '1'; let at = generator.valueToCode(block, 'AT', atOrder) || '1';
at = getListIndex(list, where, at); at = getListIndex(list, where, at);
if (mode === 'GET') { if (mode === 'GET') {
@@ -186,14 +243,15 @@ export function lists_getIndex(block, generator) {
const code = 'table.remove(' + list + ', ' + at + ')'; const code = 'table.remove(' + list + ', ' + at + ')';
if (mode === 'GET_REMOVE') { if (mode === 'GET_REMOVE') {
return [code, Order.HIGH]; return [code, Order.HIGH];
} else { // `mode` === 'REMOVE' } else {
// `mode` === 'REMOVE'
return code + '\n'; return code + '\n';
} }
} }
} }
}; }
export function lists_setIndex(block, generator) { export function lists_setIndex(block: Block, generator: LuaGenerator): string {
// 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 = generator.valueToCode(block, 'LIST', Order.HIGH) || '{}'; let list = generator.valueToCode(block, 'LIST', Order.HIGH) || '{}';
@@ -205,28 +263,41 @@ export function lists_setIndex(block, generator) {
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,
// 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.
if ((where === 'LAST' || where === 'FROM_END' || where === 'RANDOM') && if (
!list.match(/^\w+$/)) { (where === 'LAST' || where === 'FROM_END' || where === 'RANDOM') &&
!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 = const listVar = generator.nameDB_!.getDistinctName(
generator.nameDB_.getDistinctName('tmp_list', NameType.VARIABLE); 'tmp_list',
NameType.VARIABLE,
);
code = listVar + ' = ' + list + '\n'; code = listVar + ' = ' + list + '\n';
list = listVar; list = listVar;
} }
if (mode === 'SET') { if (mode === 'SET') {
code += list + '[' + getListIndex(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 +=
(getListIndex(list, where, at) + (where === 'LAST' ? ' + 1' : '')) + 'table.insert(' +
', ' + value + ')'; list +
', ' +
(getListIndex(list, where, at) + (where === 'LAST' ? ' + 1' : '')) +
', ' +
value +
')';
} }
return code + '\n'; return code + '\n';
}; }
export function lists_getSublist(block, generator) { export function lists_getSublist(
block: Block,
generator: LuaGenerator,
): [string, Order] {
// Get sublist. // Get sublist.
const list = generator.valueToCode(block, 'LIST', Order.NONE) || '{}'; const list = generator.valueToCode(block, 'LIST', Order.NONE) || '{}';
const where1 = block.getFieldValue('WHERE1'); const where1 = block.getFieldValue('WHERE1');
@@ -237,11 +308,12 @@ export function lists_getSublist(block, generator) {
// 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.
const at1Param = const at1Param =
(where1 === 'FROM_END' || where1 === 'FROM_START') ? ', at1' : ''; where1 === 'FROM_END' || where1 === 'FROM_START' ? ', at1' : '';
const at2Param = const at2Param =
(where2 === 'FROM_END' || where2 === 'FROM_START') ? ', at2' : ''; where2 === 'FROM_END' || where2 === 'FROM_START' ? ', at2' : '';
const functionName = generator.provideFunction_( const functionName = generator.provideFunction_(
'list_sublist_' + where1.toLowerCase() + '_' + where2.toLowerCase(), ` 'list_sublist_' + where1.toLowerCase() + '_' + where2.toLowerCase(),
`
function ${generator.FUNCTION_NAME_PLACEHOLDER_}(source${at1Param}${at2Param}) function ${generator.FUNCTION_NAME_PLACEHOLDER_}(source${at1Param}${at2Param})
local t = {} local t = {}
local start = ${getListIndex('source', where1, 'at1')} local start = ${getListIndex('source', where1, 'at1')}
@@ -251,23 +323,32 @@ function ${generator.FUNCTION_NAME_PLACEHOLDER_}(source${at1Param}${at2Param})
end end
return t return t
end end
`); `,
const code = functionName + '(' + list + );
// The value for 'FROM_END' and 'FROM_START' depends on `at` so we const code =
// pass it. functionName +
((where1 === 'FROM_END' || where1 === 'FROM_START') ? ', ' + at1 : '') + '(' +
((where2 === 'FROM_END' || where2 === 'FROM_START') ? ', ' + at2 : '') + list +
')'; // The value for 'FROM_END' and 'FROM_START' depends on `at` so we
// pass it.
(where1 === 'FROM_END' || where1 === 'FROM_START' ? ', ' + at1 : '') +
(where2 === 'FROM_END' || where2 === 'FROM_START' ? ', ' + at2 : '') +
')';
return [code, Order.HIGH]; return [code, Order.HIGH];
}; }
export function lists_sort(block, generator) { export function lists_sort(
block: Block,
generator: LuaGenerator,
): [string, Order] {
// Block for sorting a list. // Block for sorting a list.
const list = generator.valueToCode(block, 'LIST', Order.NONE) || '{}'; const list = generator.valueToCode(block, 'LIST', 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 = generator.provideFunction_('list_sort', ` const functionName = generator.provideFunction_(
'list_sort',
`
function ${generator.FUNCTION_NAME_PLACEHOLDER_}(list, typev, direction) function ${generator.FUNCTION_NAME_PLACEHOLDER_}(list, typev, direction)
local t = {} local t = {}
for n,v in pairs(list) do table.insert(t, v) end for n,v in pairs(list) do table.insert(t, v) end
@@ -288,25 +369,30 @@ function ${generator.FUNCTION_NAME_PLACEHOLDER_}(list, typev, direction)
table.sort(t, compare) table.sort(t, compare)
return t return t
end end
`); `,
);
const code = const code =
functionName + '(' + list + ',"' + type + '", ' + direction + ')'; functionName + '(' + list + ',"' + type + '", ' + direction + ')';
return [code, Order.HIGH]; return [code, Order.HIGH];
}; }
export function lists_split(block, generator) { export function lists_split(
block: Block,
generator: LuaGenerator,
): [string, Order] {
// 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 = generator.valueToCode(block, 'INPUT', Order.NONE); let input = generator.valueToCode(block, 'INPUT', Order.NONE);
const delimiter = const delimiter = generator.valueToCode(block, 'DELIM', Order.NONE) || "''";
generator.valueToCode(block, 'DELIM', 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 = generator.provideFunction_('list_string_split', ` functionName = generator.provideFunction_(
'list_string_split',
`
function ${generator.FUNCTION_NAME_PLACEHOLDER_}(input, delim) function ${generator.FUNCTION_NAME_PLACEHOLDER_}(input, delim)
local t = {} local t = {}
local pos = 1 local pos = 1
@@ -322,7 +408,8 @@ function ${generator.FUNCTION_NAME_PLACEHOLDER_}(input, delim)
end end
return t return t
end end
`); `,
);
} else if (mode === 'JOIN') { } else if (mode === 'JOIN') {
if (!input) { if (!input) {
input = '{}'; input = '{}';
@@ -333,12 +420,17 @@ end
} }
const code = functionName + '(' + input + ', ' + delimiter + ')'; const code = functionName + '(' + input + ', ' + delimiter + ')';
return [code, Order.HIGH]; return [code, Order.HIGH];
}; }
export function lists_reverse(block, generator) { export function lists_reverse(
block: Block,
generator: LuaGenerator,
): [string, Order] {
// Block for reversing a list. // Block for reversing a list.
const list = generator.valueToCode(block, 'LIST', Order.NONE) || '{}'; const list = generator.valueToCode(block, 'LIST', Order.NONE) || '{}';
const functionName = generator.provideFunction_('list_reverse', ` const functionName = generator.provideFunction_(
'list_reverse',
`
function ${generator.FUNCTION_NAME_PLACEHOLDER_}(input) function ${generator.FUNCTION_NAME_PLACEHOLDER_}(input)
local reversed = {} local reversed = {}
for i = #input, 1, -1 do for i = #input, 1, -1 do
@@ -346,7 +438,8 @@ function ${generator.FUNCTION_NAME_PLACEHOLDER_}(input)
end end
return reversed return reversed
end end
`); `,
);
const code = functionName + '(' + list + ')'; const code = functionName + '(' + list + ')';
return [code, Order.HIGH]; return [code, Order.HIGH];
}; }

View File

@@ -5,15 +5,16 @@
*/ */
/** /**
* @fileoverview Generating Lua for logic blocks. * @file Generating Lua for logic blocks.
*/ */
// Former goog.module ID: Blockly.Lua.logic // Former goog.module ID: Blockly.Lua.logic
import type {Block} from '../../core/block.js';
import type {LuaGenerator} from './lua_generator.js';
import {Order} from './lua_generator.js'; import {Order} from './lua_generator.js';
export function controls_if(block: Block, generator: LuaGenerator): string {
export function controls_if(block, generator) {
// If/elseif/else condition. // If/elseif/else condition.
let n = 0; let n = 0;
let code = ''; let code = '';
@@ -23,15 +24,17 @@ export function controls_if(block, generator) {
} }
do { do {
const conditionCode = const conditionCode =
generator.valueToCode(block, 'IF' + n, Order.NONE) || 'false'; generator.valueToCode(block, 'IF' + n, Order.NONE) || 'false';
let branchCode = generator.statementToCode(block, 'DO' + n); let branchCode = generator.statementToCode(block, 'DO' + n);
if (generator.STATEMENT_SUFFIX) { if (generator.STATEMENT_SUFFIX) {
branchCode = generator.prefixLines( branchCode =
generator.prefixLines(
generator.injectId(generator.STATEMENT_SUFFIX, block), generator.injectId(generator.STATEMENT_SUFFIX, block),
generator.INDENT) + branchCode; generator.INDENT,
) + branchCode;
} }
code += code +=
(n > 0 ? 'else' : '') + '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));
@@ -39,36 +42,46 @@ export function controls_if(block, generator) {
let branchCode = generator.statementToCode(block, 'ELSE'); let branchCode = generator.statementToCode(block, 'ELSE');
if (generator.STATEMENT_SUFFIX) { if (generator.STATEMENT_SUFFIX) {
branchCode = branchCode =
generator.prefixLines( generator.prefixLines(
generator.injectId( generator.injectId(generator.STATEMENT_SUFFIX, block),
generator.STATEMENT_SUFFIX, block), generator.INDENT,
generator.INDENT) + ) + branchCode;
branchCode;
} }
code += 'else\n' + branchCode; code += 'else\n' + branchCode;
} }
return code + 'end\n'; return code + 'end\n';
}; }
export const controls_ifelse = controls_if; export const controls_ifelse = controls_if;
export function logic_compare(block, generator) { export function logic_compare(
block: Block,
generator: LuaGenerator,
): [string, Order] {
// Comparison operator. // Comparison operator.
const OPERATORS = const OPERATORS = {
{'EQ': '==', 'NEQ': '~=', 'LT': '<', 'LTE': '<=', 'GT': '>', 'GTE': '>='}; 'EQ': '==',
const operator = OPERATORS[block.getFieldValue('OP')]; 'NEQ': '~=',
const argument0 = 'LT': '<',
generator.valueToCode(block, 'A', Order.RELATIONAL) || '0'; 'LTE': '<=',
const argument1 = 'GT': '>',
generator.valueToCode(block, 'B', Order.RELATIONAL) || '0'; 'GTE': '>=',
};
type OperatorOption = keyof typeof OPERATORS;
const operator = OPERATORS[block.getFieldValue('OP') as OperatorOption];
const argument0 = generator.valueToCode(block, 'A', Order.RELATIONAL) || '0';
const argument1 = generator.valueToCode(block, 'B', Order.RELATIONAL) || '0';
const code = argument0 + ' ' + operator + ' ' + argument1; const code = argument0 + ' ' + operator + ' ' + argument1;
return [code, Order.RELATIONAL]; return [code, Order.RELATIONAL];
}; }
export function logic_operation(block, generator) { export function logic_operation(
block: Block,
generator: LuaGenerator,
): [string, Order] {
// 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') ? Order.AND : Order.OR; const order = operator === 'and' ? Order.AND : Order.OR;
let argument0 = generator.valueToCode(block, 'A', order); let argument0 = generator.valueToCode(block, 'A', order);
let argument1 = generator.valueToCode(block, 'B', order); let argument1 = generator.valueToCode(block, 'B', order);
if (!argument0 && !argument1) { if (!argument0 && !argument1) {
@@ -77,7 +90,7 @@ export function logic_operation(block, generator) {
argument1 = 'false'; argument1 = 'false';
} else { } else {
// Single missing arguments have no effect on the return value. // Single missing arguments have no effect on the return value.
const defaultArgument = (operator === 'and') ? 'true' : 'false'; const defaultArgument = operator === 'and' ? 'true' : 'false';
if (!argument0) { if (!argument0) {
argument0 = defaultArgument; argument0 = defaultArgument;
} }
@@ -87,33 +100,43 @@ export function logic_operation(block, generator) {
} }
const code = argument0 + ' ' + operator + ' ' + argument1; const code = argument0 + ' ' + operator + ' ' + argument1;
return [code, order]; return [code, order];
}; }
export function logic_negate(block, generator) { export function logic_negate(
block: Block,
generator: LuaGenerator,
): [string, Order] {
// Negation. // Negation.
const argument0 = const argument0 = generator.valueToCode(block, 'BOOL', Order.UNARY) || 'true';
generator.valueToCode(block, 'BOOL', Order.UNARY) || 'true';
const code = 'not ' + argument0; const code = 'not ' + argument0;
return [code, Order.UNARY]; return [code, Order.UNARY];
}; }
export function logic_boolean(block, generator) { export function logic_boolean(
block: Block,
generator: LuaGenerator,
): [string, Order] {
// 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, Order.ATOMIC]; return [code, Order.ATOMIC];
}; }
export function logic_null(block, generator) { export function logic_null(
block: Block,
generator: LuaGenerator,
): [string, Order] {
// Null data type. // Null data type.
return ['nil', Order.ATOMIC]; return ['nil', Order.ATOMIC];
}; }
export function logic_ternary(block, generator) { export function logic_ternary(
block: Block,
generator: LuaGenerator,
): [string, Order] {
// Ternary operator. // Ternary operator.
const value_if = generator.valueToCode(block, 'IF', Order.AND) || 'false'; const value_if = generator.valueToCode(block, 'IF', Order.AND) || 'false';
const value_then = const value_then = generator.valueToCode(block, 'THEN', Order.AND) || 'nil';
generator.valueToCode(block, 'THEN', Order.AND) || 'nil';
const value_else = generator.valueToCode(block, 'ELSE', Order.OR) || 'nil'; const value_else = generator.valueToCode(block, 'ELSE', 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, Order.OR]; return [code, Order.OR];
}; }

View File

@@ -5,21 +5,22 @@
*/ */
/** /**
* @fileoverview Generating Lua for loop blocks. * @file Generating Lua for loop blocks.
*/ */
// Former goog.module ID: Blockly.Lua.loops // Former goog.module ID: Blockly.Lua.loops
import * as stringUtils from '../../core/utils/string.js'; import * as stringUtils from '../../core/utils/string.js';
import type {Block} from '../../core/block.js';
import type {ControlFlowInLoopBlock} from '../../blocks/loops.js';
import type {LuaGenerator} from './lua_generator.js';
import {NameType} from '../../core/names.js'; import {NameType} from '../../core/names.js';
import {Order} from './lua_generator.js'; import {Order} from './lua_generator.js';
/** /**
* This is the text used to implement a <pre>continue</pre>. * This is the text used to implement a <pre>continue</pre>.
* It is also used to recognise <pre>continue</pre>s in generated code so that * It is also used to recognise <pre>continue</pre>s in generated code so that
* 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 CONTINUE_STATEMENT = 'goto continue\n'; const CONTINUE_STATEMENT = 'goto continue\n';
@@ -29,20 +30,23 @@ const CONTINUE_STATEMENT = 'goto continue\n';
* in all outer loops, but this is safer than duplicating the logic of * in all outer loops, but this is safer than duplicating the logic of
* blockToCode. * blockToCode.
* *
* @param {string} branch Generated code of the loop body * @param branch Generated code of the loop body
* @param {string} indent Whitespace by which to indent a continue statement. * @param indent Whitespace by which to indent a continue statement.
* @return {string} Generated label or '' if unnecessary * @returns Generated label or '' if unnecessary
*/ */
function addContinueLabel(branch, indent) { function addContinueLabel(branch: string, indent: string): string {
if (branch.indexOf(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 + indent + '::continue::\n'; return branch + indent + '::continue::\n';
} else { } else {
return branch; return branch;
} }
}; }
export function controls_repeat_ext(block, generator) { export function controls_repeat_ext(
block: Block,
generator: LuaGenerator,
): string {
// Repeat n times. // Repeat n times.
let repeats; let repeats;
if (block.getField('TIMES')) { if (block.getField('TIMES')) {
@@ -60,21 +64,26 @@ export function controls_repeat_ext(block, generator) {
let branch = generator.statementToCode(block, 'DO'); let branch = generator.statementToCode(block, 'DO');
branch = generator.addLoopTrap(branch, block); branch = generator.addLoopTrap(branch, block);
branch = addContinueLabel(branch, generator.INDENT); branch = addContinueLabel(branch, generator.INDENT);
const loopVar = generator.nameDB_.getDistinctName('count', NameType.VARIABLE); const loopVar = generator.nameDB_!.getDistinctName(
'count',
NameType.VARIABLE,
);
const code = const code =
'for ' + loopVar + ' = 1, ' + repeats + ' do\n' + branch + 'end\n'; 'for ' + loopVar + ' = 1, ' + repeats + ' do\n' + branch + 'end\n';
return code; return code;
}; }
export const controls_repeat = controls_repeat_ext; export const controls_repeat = controls_repeat_ext;
export function controls_whileUntil(block, generator) { export function controls_whileUntil(
block: Block,
generator: LuaGenerator,
): string {
// Do while/until loop. // Do while/until loop.
const until = block.getFieldValue('MODE') === 'UNTIL'; const until = block.getFieldValue('MODE') === 'UNTIL';
let argument0 = let argument0 =
generator.valueToCode( generator.valueToCode(block, 'BOOL', until ? Order.UNARY : Order.NONE) ||
block, 'BOOL', until ? Order.UNARY : Order.NONE) || 'false';
'false';
let branch = generator.statementToCode(block, 'DO'); let branch = generator.statementToCode(block, 'DO');
branch = generator.addLoopTrap(branch, block); branch = generator.addLoopTrap(branch, block);
branch = addContinueLabel(branch, generator.INDENT); branch = addContinueLabel(branch, generator.INDENT);
@@ -82,12 +91,11 @@ export function controls_whileUntil(block, generator) {
argument0 = 'not ' + argument0; argument0 = 'not ' + argument0;
} }
return 'while ' + argument0 + ' do\n' + branch + 'end\n'; return 'while ' + argument0 + ' do\n' + branch + 'end\n';
}; }
export function controls_for(block, generator) { export function controls_for(block: Block, generator: LuaGenerator): string {
// For loop. // For loop.
const variable0 = const variable0 = generator.getVariableName(block.getFieldValue('VAR'));
generator.getVariableName(block.getFieldValue('VAR'));
const startVar = generator.valueToCode(block, 'FROM', Order.NONE) || '0'; const startVar = generator.valueToCode(block, 'FROM', Order.NONE) || '0';
const endVar = generator.valueToCode(block, 'TO', Order.NONE) || '0'; const endVar = generator.valueToCode(block, 'TO', Order.NONE) || '0';
const increment = generator.valueToCode(block, 'BY', Order.NONE) || '1'; const increment = generator.valueToCode(block, 'BY', Order.NONE) || '1';
@@ -96,8 +104,11 @@ export function controls_for(block, generator) {
branch = addContinueLabel(branch, generator.INDENT); branch = addContinueLabel(branch, generator.INDENT);
let code = ''; let code = '';
let incValue; let incValue;
if (stringUtils.isNumber(startVar) && stringUtils.isNumber(endVar) && if (
stringUtils.isNumber(increment)) { stringUtils.isNumber(startVar) &&
stringUtils.isNumber(endVar) &&
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));
@@ -106,12 +117,13 @@ export function controls_for(block, generator) {
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 = incValue = generator.nameDB_!.getDistinctName(
generator.nameDB_.getDistinctName( variable0 + '_inc',
variable0 + '_inc', NameType.VARIABLE); NameType.VARIABLE,
);
code += incValue + ' = '; code += incValue + ' = ';
if (stringUtils.isNumber(increment)) { if (stringUtils.isNumber(increment)) {
code += Math.abs(increment) + '\n'; code += Math.abs(increment as unknown as number) + '\n';
} else { } else {
code += 'math.abs(' + increment + ')\n'; code += 'math.abs(' + increment + ')\n';
} }
@@ -120,25 +132,36 @@ export function controls_for(block, generator) {
code += 'end\n'; code += 'end\n';
} }
code += code +=
'for ' + variable0 + ' = ' + startVar + ', ' + endVar + ', ' + incValue; 'for ' + variable0 + ' = ' + startVar + ', ' + endVar + ', ' + incValue;
code += ' do\n' + branch + 'end\n'; code += ' do\n' + branch + 'end\n';
return code; return code;
}; }
export function controls_forEach(block, generator) { export function controls_forEach(
block: Block,
generator: LuaGenerator,
): string {
// For each loop. // For each loop.
const variable0 = const variable0 = generator.getVariableName(block.getFieldValue('VAR'));
generator.getVariableName(block.getFieldValue('VAR'));
const argument0 = generator.valueToCode(block, 'LIST', Order.NONE) || '{}'; const argument0 = generator.valueToCode(block, 'LIST', Order.NONE) || '{}';
let branch = generator.statementToCode(block, 'DO'); let branch = generator.statementToCode(block, 'DO');
branch = generator.addLoopTrap(branch, block); branch = generator.addLoopTrap(branch, block);
branch = addContinueLabel(branch, generator.INDENT); branch = addContinueLabel(branch, generator.INDENT);
const code = 'for _, ' + variable0 + ' in ipairs(' + argument0 + ') do \n' + const code =
branch + 'end\n'; 'for _, ' +
variable0 +
' in ipairs(' +
argument0 +
') do \n' +
branch +
'end\n';
return code; return code;
}; }
export function controls_flow_statements(block, generator) { export function controls_flow_statements(
block: Block,
generator: LuaGenerator,
): string {
// Flow statements: continue, break. // Flow statements: continue, break.
let xfix = ''; let xfix = '';
if (generator.STATEMENT_PREFIX) { if (generator.STATEMENT_PREFIX) {
@@ -151,7 +174,7 @@ export function controls_flow_statements(block, generator) {
xfix += generator.injectId(generator.STATEMENT_SUFFIX, block); xfix += generator.injectId(generator.STATEMENT_SUFFIX, block);
} }
if (generator.STATEMENT_PREFIX) { if (generator.STATEMENT_PREFIX) {
const loop = block.getSurroundLoop(); const loop = (block as ControlFlowInLoopBlock).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.
@@ -166,4 +189,4 @@ export function controls_flow_statements(block, generator) {
return xfix + CONTINUE_STATEMENT; return xfix + CONTINUE_STATEMENT;
} }
throw Error('Unknown flow statement.'); throw Error('Unknown flow statement.');
}; }

View File

@@ -5,40 +5,40 @@
*/ */
/** /**
* @fileoverview Helper functions for generating Lua for blocks. * @file Lua code generator class, including helper methods for
* generating Lua for blocks.
*
* Based on Ellen Spertus's blocky-lua project. * Based on Ellen Spertus's blocky-lua project.
* @suppress {checkTypes|globalThis}
*/ */
// Former goog.module ID: Blockly.Lua // Former goog.module ID: Blockly.Lua
import * as stringUtils from '../../core/utils/string.js'; import * as stringUtils from '../../core/utils/string.js';
// import type {Block} from '../../core/block.js'; import type {Block} from '../../core/block.js';
import {CodeGenerator} from '../../core/generator.js'; import {CodeGenerator} from '../../core/generator.js';
import {Names} from '../../core/names.js'; import {Names} from '../../core/names.js';
// import type {Workspace} from '../../core/workspace.js'; import type {Workspace} from '../../core/workspace.js';
import {inputTypes} from '../../core/inputs/input_types.js'; import {inputTypes} from '../../core/inputs/input_types.js';
/** /**
* Order of operation ENUMs. * Order of operation ENUMs.
* http://www.lua.org/manual/5.3/manual.html#3.4.8 * http://www.lua.org/manual/5.3/manual.html#3.4.8
* @enum {number}
*/ */
export const Order = { // prettier-ignore
ATOMIC: 0, // literals export enum Order {
ATOMIC = 0, // literals
// The next level was not explicit in documentation and inferred by Ellen. // The next level was not explicit in documentation and inferred by Ellen.
HIGH: 1, // Function calls, tables[] HIGH = 1, // Function calls, tables[]
EXPONENTIATION: 2, // ^ EXPONENTIATION = 2, // ^
UNARY: 3, // not # - ~ UNARY = 3, // not # - ~
MULTIPLICATIVE: 4, // * / % MULTIPLICATIVE = 4, // * / %
ADDITIVE: 5, // + - ADDITIVE = 5, // + -
CONCATENATION: 6, // .. CONCATENATION = 6, // ..
RELATIONAL: 7, // < > <= >= ~= == RELATIONAL = 7, // < > <= >= ~= ==
AND: 8, // and AND = 8, // and
OR: 9, // or OR = 9, // or
NONE: 99, NONE = 99,
}; }
/** /**
* Lua code generator class. * Lua code generator class.
@@ -48,8 +48,8 @@ export const Order = {
* option used for lists and text. * option used for lists and text.
*/ */
export class LuaGenerator extends CodeGenerator { export class LuaGenerator extends CodeGenerator {
constructor(name) { constructor(name = 'Lua') {
super(name ?? 'Lua'); super(name);
this.isInitialized = false; this.isInitialized = false;
// Copy Order values onto instance for backwards compatibility // Copy Order values onto instance for backwards compatibility
@@ -60,7 +60,16 @@ export class LuaGenerator extends CodeGenerator {
// replace data properties with get accessors that call // replace data properties with get accessors that call
// deprecate.warn().) // deprecate.warn().)
for (const key in Order) { for (const key in Order) {
this['ORDER_' + key] = Order[key]; // Must assign Order[key] to a temporary to get the type guard to work;
// see https://github.com/microsoft/TypeScript/issues/10530.
const value = Order[key];
// Skip reverse-lookup entries in the enum. Due to
// https://github.com/microsoft/TypeScript/issues/55713 this (as
// of TypeScript 5.5.2) actually narrows the type of value to
// never - but that still allows the following assignment to
// succeed.
if (typeof value === 'string') continue;
(this as unknown as Record<string, Order>)['ORDER_' + key] = value;
} }
// List of illegal variable names. This is not intended to be a // List of illegal variable names. This is not intended to be a
@@ -70,38 +79,39 @@ export class LuaGenerator extends CodeGenerator {
this.addReservedWords( this.addReservedWords(
// Special character // Special character
'_,' + '_,' +
// From theoriginalbit's script: // From theoriginalbit's script:
// https://github.com/espertus/blockly-lua/issues/6 // https://github.com/espertus/blockly-lua/issues/6
'__inext,assert,bit,colors,colours,coroutine,disk,dofile,error,fs,' + '__inext,assert,bit,colors,colours,coroutine,disk,dofile,error,fs,' +
'fetfenv,getmetatable,gps,help,io,ipairs,keys,loadfile,loadstring,math,' + 'fetfenv,getmetatable,gps,help,io,ipairs,keys,loadfile,loadstring,math,' +
'native,next,os,paintutils,pairs,parallel,pcall,peripheral,print,' + 'native,next,os,paintutils,pairs,parallel,pcall,peripheral,print,' +
'printError,rawequal,rawget,rawset,read,rednet,redstone,rs,select,' + 'printError,rawequal,rawget,rawset,read,rednet,redstone,rs,select,' +
'setfenv,setmetatable,sleep,string,table,term,textutils,tonumber,' + 'setfenv,setmetatable,sleep,string,table,term,textutils,tonumber,' +
'tostring,turtle,type,unpack,vector,write,xpcall,_VERSION,__indext,' + 'tostring,turtle,type,unpack,vector,write,xpcall,_VERSION,__indext,' +
// Not included in the script, probably because it wasn't enabled: // Not included in the script, probably because it wasn't enabled:
'HTTP,' + 'HTTP,' +
// Keywords (http://www.lua.org/pil/1.3.html). // Keywords (http://www.lua.org/pil/1.3.html).
'and,break,do,else,elseif,end,false,for,function,if,in,local,nil,not,' + 'and,break,do,else,elseif,end,false,for,function,if,in,local,nil,not,' +
'or,repeat,return,then,true,until,while,' + 'or,repeat,return,then,true,until,while,' +
// Metamethods (http://www.lua.org/manual/5.2/manual.html). // Metamethods (http://www.lua.org/manual/5.2/manual.html).
'add,sub,mul,div,mod,pow,unm,concat,len,eq,lt,le,index,newindex,call,' + 'add,sub,mul,div,mod,pow,unm,concat,len,eq,lt,le,index,newindex,call,' +
// Basic functions (http://www.lua.org/manual/5.2/manual.html, // Basic functions (http://www.lua.org/manual/5.2/manual.html,
// section 6.1). // section 6.1).
'assert,collectgarbage,dofile,error,_G,getmetatable,inpairs,load,' + 'assert,collectgarbage,dofile,error,_G,getmetatable,inpairs,load,' +
'loadfile,next,pairs,pcall,print,rawequal,rawget,rawlen,rawset,select,' + 'loadfile,next,pairs,pcall,print,rawequal,rawget,rawlen,rawset,select,' +
'setmetatable,tonumber,tostring,type,_VERSION,xpcall,' + 'setmetatable,tonumber,tostring,type,_VERSION,xpcall,' +
// Modules (http://www.lua.org/manual/5.2/manual.html, section 6.3). // Modules (http://www.lua.org/manual/5.2/manual.html, section 6.3).
'require,package,string,table,math,bit32,io,file,os,debug' 'require,package,string,table,math,bit32,io,file,os,debug',
); );
} }
/** /**
* Initialise the database of variable names. * Initialise the database of variable names.
* @param {!Workspace} workspace Workspace to generate code from. *
* @param workspace Workspace to generate code from.
*/ */
init(workspace) { init(workspace: Workspace) {
// Call Blockly.CodeGenerator's init. // Call Blockly.CodeGenerator's init.
super.init(); super.init(workspace);
if (!this.nameDB_) { if (!this.nameDB_) {
this.nameDB_ = new Names(this.RESERVED_WORDS_); this.nameDB_ = new Names(this.RESERVED_WORDS_);
@@ -113,73 +123,77 @@ export class LuaGenerator extends CodeGenerator {
this.nameDB_.populateProcedures(workspace); this.nameDB_.populateProcedures(workspace);
this.isInitialized = true; this.isInitialized = true;
}; }
/** /**
* Prepend the generated code with the variable definitions. * Prepend the generated code with the variable definitions.
* @param {string} code Generated code. *
* @return {string} Completed code. * @param code Generated code.
* @returns Completed code.
*/ */
finish(code) { finish(code: string): string {
// Convert the definitions dictionary into a list. // Convert the definitions dictionary into a list.
const definitions = Object.values(this.definitions_); const definitions = Object.values(this.definitions_);
// Call Blockly.CodeGenerator's finish. // Call Blockly.CodeGenerator's finish.
code = super.finish(code); code = super.finish(code);
this.isInitialized = false; this.isInitialized = false;
this.nameDB_.reset(); this.nameDB_!.reset();
return definitions.join('\n\n') + '\n\n\n' + code; return definitions.join('\n\n') + '\n\n\n' + code;
}; }
/** /**
* Naked values are top-level blocks with outputs that aren't plugged into * Naked values are top-level blocks with outputs that aren't plugged into
* anything. In Lua, an expression is not a legal statement, so we must assign * anything. In Lua, an expression is not a legal statement, so we must assign
* the value to the (conventionally ignored) _. * the value to the (conventionally ignored) _.
* http://lua-users.org/wiki/ExpressionsAsStatements * http://lua-users.org/wiki/ExpressionsAsStatements
* @param {string} line Line of generated code. *
* @return {string} Legal line of code. * @param line Line of generated code.
* @return Legal line of code.
*/ */
scrubNakedValue(line) { scrubNakedValue(line: string): string {
return 'local _ = ' + line + '\n'; return 'local _ = ' + line + '\n';
}; }
/** /**
* Encode a string as a properly escaped Lua string, complete with * Encode a string as a properly escaped Lua string, complete with
* quotes. * quotes.
* @param {string} string Text to encode. *
* @return {string} Lua string. * @param string Text to encode.
* @returns Lua string.
*/ */
quote_(string) { quote_(string: string): string {
string = string.replace(/\\/g, '\\\\') string = string
.replace(/\n/g, '\\\n') .replace(/\\/g, '\\\\')
.replace(/'/g, '\\\''); .replace(/\n/g, '\\\n')
return '\'' + string + '\''; .replace(/'/g, "\\'");
}; return "'" + string + "'";
}
/** /**
* Encode a string as a properly escaped multiline Lua string, complete with * Encode a string as a properly escaped multiline Lua string, complete with
* quotes. * quotes.
* @param {string} string Text to encode. *
* @return {string} Lua string. * @param string Text to encode.
* @returns Lua string.
*/ */
multiline_quote_(string) { multiline_quote_(string: string): string {
const lines = string.split(/\n/g).map(this.quote_); const lines = string.split(/\n/g).map(this.quote_);
// Join with the following, plus a newline: // Join with the following, plus a newline:
// .. '\n' .. // .. '\n' ..
return lines.join(' .. \'\\n\' ..\n'); return lines.join(" .. '\\n' ..\n");
}; }
/** /**
* Common tasks for generating Lua from blocks. * Common tasks for generating Lua from blocks.
* Handles comments for the specified block and any connected value blocks. * Handles comments for the specified block and any connected value blocks.
* Calls any statements following this block. * Calls any statements following this block.
* @param {!Block} block The current block. * @param block The current block.
* @param {string} code The Lua code created for this block. * @param code The Lua code created for this block.
* @param {boolean=} opt_thisOnly True to generate code for only this statement. * @param thisOnly True to generate code for only this statement.
* @return {string} Lua code with comments and subsequent blocks added. * @returns Lua code with comments and subsequent blocks added.
* @protected
*/ */
scrub_(block, code, opt_thisOnly) { scrub_(block: Block, code: string, thisOnly = false): string {
let commentCode = ''; let commentCode = '';
// Only collect comments for blocks that aren't inline. // Only collect comments for blocks that aren't inline.
if (!block.outputConnection || !block.outputConnection.targetConnection) { if (!block.outputConnection || !block.outputConnection.targetConnection) {
@@ -193,7 +207,7 @@ export class LuaGenerator extends CodeGenerator {
// Don't collect comments for nested statements. // Don't collect comments for nested statements.
for (let i = 0; i < block.inputList.length; i++) { for (let i = 0; i < block.inputList.length; i++) {
if (block.inputList[i].type === inputTypes.VALUE) { if (block.inputList[i].type === inputTypes.VALUE) {
const childBlock = block.inputList[i].connection.targetBlock(); const childBlock = block.inputList[i].connection!.targetBlock();
if (childBlock) { if (childBlock) {
comment = this.allNestedComments(childBlock); comment = this.allNestedComments(childBlock);
if (comment) { if (comment) {
@@ -203,8 +217,9 @@ export class LuaGenerator extends CodeGenerator {
} }
} }
} }
const nextBlock = block.nextConnection && block.nextConnection.targetBlock(); const nextBlock =
const nextCode = opt_thisOnly ? '' : this.blockToCode(nextBlock); block.nextConnection && block.nextConnection.targetBlock();
const nextCode = thisOnly ? '' : this.blockToCode(nextBlock);
return commentCode + code + nextCode; return commentCode + code + nextCode;
}; }
} }

View File

@@ -5,40 +5,51 @@
*/ */
/** /**
* @fileoverview Generating Lua for math blocks. * @file Generating Lua for math blocks.
*/ */
// Former goog.module ID: Blockly.Lua.math // Former goog.module ID: Blockly.Lua.math
import type {Block} from '../../core/block.js';
import type {LuaGenerator} from './lua_generator.js';
import {Order} from './lua_generator.js'; import {Order} from './lua_generator.js';
export function math_number(
export function math_number(block, generator) { block: Block,
generator: LuaGenerator,
): [string, Order] {
// Numeric value. // Numeric value.
const code = Number(block.getFieldValue('NUM')); const code = Number(block.getFieldValue('NUM'));
const order = code < 0 ? Order.UNARY : Order.ATOMIC; const order = code < 0 ? Order.UNARY : Order.ATOMIC;
return [code, order]; return [String(code), order];
}; }
export function math_arithmetic(block, generator) { export function math_arithmetic(
block: Block,
generator: LuaGenerator,
): [string, Order] {
// Basic arithmetic operators, and power. // Basic arithmetic operators, and power.
const OPERATORS = { const OPERATORS: Record<string, [string, Order]> = {
'ADD': [' + ', Order.ADDITIVE], 'ADD': [' + ', Order.ADDITIVE],
'MINUS': [' - ', Order.ADDITIVE], 'MINUS': [' - ', Order.ADDITIVE],
'MULTIPLY': [' * ', Order.MULTIPLICATIVE], 'MULTIPLY': [' * ', Order.MULTIPLICATIVE],
'DIVIDE': [' / ', Order.MULTIPLICATIVE], 'DIVIDE': [' / ', Order.MULTIPLICATIVE],
'POWER': [' ^ ', Order.EXPONENTIATION], 'POWER': [' ^ ', Order.EXPONENTIATION],
}; };
const tuple = OPERATORS[block.getFieldValue('OP')]; type OperatorOption = keyof typeof OPERATORS;
const tuple = OPERATORS[block.getFieldValue('OP') as OperatorOption];
const operator = tuple[0]; const operator = tuple[0];
const order = tuple[1]; const order = tuple[1];
const argument0 = generator.valueToCode(block, 'A', order) || '0'; const argument0 = generator.valueToCode(block, 'A', order) || '0';
const argument1 = generator.valueToCode(block, 'B', order) || '0'; const argument1 = generator.valueToCode(block, 'B', order) || '0';
const code = argument0 + operator + argument1; const code = argument0 + operator + argument1;
return [code, order]; return [code, order];
}; }
export function math_single(block, generator) { export function math_single(
block: Block,
generator: LuaGenerator,
): [string, Order] {
// Math operators with single operand. // Math operators with single operand.
const operator = block.getFieldValue('OP'); const operator = block.getFieldValue('OP');
let arg; let arg;
@@ -106,11 +117,14 @@ export function math_single(block, generator) {
throw Error('Unknown math operator: ' + operator); throw Error('Unknown math operator: ' + operator);
} }
return [code, Order.HIGH]; return [code, Order.HIGH];
}; }
export function math_constant(block, generator) { export function math_constant(
block: Block,
generator: LuaGenerator,
): [string, Order] {
// 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: Record<string, [string, Order]> = {
'PI': ['math.pi', Order.HIGH], 'PI': ['math.pi', Order.HIGH],
'E': ['math.exp(1)', Order.HIGH], 'E': ['math.exp(1)', Order.HIGH],
'GOLDEN_RATIO': ['(1 + math.sqrt(5)) / 2', Order.MULTIPLICATIVE], 'GOLDEN_RATIO': ['(1 + math.sqrt(5)) / 2', Order.MULTIPLICATIVE],
@@ -119,12 +133,15 @@ export function math_constant(block, generator) {
'INFINITY': ['math.huge', Order.HIGH], 'INFINITY': ['math.huge', Order.HIGH],
}; };
return CONSTANTS[block.getFieldValue('CONSTANT')]; return CONSTANTS[block.getFieldValue('CONSTANT')];
}; }
export function math_number_property(block, generator) { export function math_number_property(
block: Block,
generator: LuaGenerator,
): [string, Order] {
// 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 PROPERTIES = { const PROPERTIES: Record<string, [string | null, Order, Order]> = {
'EVEN': [' % 2 == 0', Order.MULTIPLICATIVE, Order.RELATIONAL], 'EVEN': [' % 2 == 0', Order.MULTIPLICATIVE, Order.RELATIONAL],
'ODD': [' % 2 == 1', Order.MULTIPLICATIVE, Order.RELATIONAL], 'ODD': [' % 2 == 1', Order.MULTIPLICATIVE, Order.RELATIONAL],
'WHOLE': [' % 1 == 0', Order.MULTIPLICATIVE, Order.RELATIONAL], 'WHOLE': [' % 1 == 0', Order.MULTIPLICATIVE, Order.RELATIONAL],
@@ -135,12 +152,14 @@ export function math_number_property(block, generator) {
}; };
const dropdownProperty = block.getFieldValue('PROPERTY'); const dropdownProperty = block.getFieldValue('PROPERTY');
const [suffix, inputOrder, outputOrder] = PROPERTIES[dropdownProperty]; const [suffix, inputOrder, outputOrder] = PROPERTIES[dropdownProperty];
const numberToCheck = generator.valueToCode(block, 'NUMBER_TO_CHECK', const numberToCheck =
inputOrder) || '0'; generator.valueToCode(block, 'NUMBER_TO_CHECK', inputOrder) || '0';
let code; let code;
if (dropdownProperty === 'PRIME') { if (dropdownProperty === '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 = generator.provideFunction_('math_isPrime', ` const functionName = generator.provideFunction_(
'math_isPrime',
`
function ${generator.FUNCTION_NAME_PLACEHOLDER_}(n) function ${generator.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 if n == 2 or n == 3 then
@@ -159,11 +178,12 @@ function ${generator.FUNCTION_NAME_PLACEHOLDER_}(n)
end end
return true return true
end end
`); `,
);
code = functionName + '(' + numberToCheck + ')'; code = functionName + '(' + numberToCheck + ')';
} else if (dropdownProperty === 'DIVISIBLE_BY') { } else if (dropdownProperty === 'DIVISIBLE_BY') {
const divisor = generator.valueToCode(block, 'DIVISOR', const divisor =
Order.MULTIPLICATIVE) || '0'; generator.valueToCode(block, 'DIVISOR', Order.MULTIPLICATIVE) || '0';
// If 'divisor' is some code that evals to 0, generator will produce a nan. // If 'divisor' is some code that evals to 0, generator 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 === '0') { if (divisor === '0') {
@@ -177,23 +197,25 @@ end
code = numberToCheck + suffix; code = numberToCheck + suffix;
} }
return [code, outputOrder]; return [code, outputOrder];
}; }
export function math_change(block, generator) { export function math_change(block: Block, generator: LuaGenerator): string {
// Add to a variable in place. // Add to a variable in place.
const argument0 = const argument0 =
generator.valueToCode(block, 'DELTA', Order.ADDITIVE) || '0'; generator.valueToCode(block, 'DELTA', Order.ADDITIVE) || '0';
const varName = const varName = generator.getVariableName(block.getFieldValue('VAR'));
generator.getVariableName(block.getFieldValue('VAR'));
return varName + ' = ' + varName + ' + ' + argument0 + '\n'; return varName + ' = ' + varName + ' + ' + argument0 + '\n';
}; }
// Rounding functions have a single operand. // Rounding functions have a single operand.
export const math_round = math_single; export const math_round = math_single;
// Trigonometry functions have a single operand. // Trigonometry functions have a single operand.
export const math_trig = math_single; export const math_trig = math_single;
export function math_on_list(block, generator) { export function math_on_list(
block: Block,
generator: LuaGenerator,
): [string, Order] {
// Math functions for lists. // Math functions for lists.
const func = block.getFieldValue('OP'); const func = block.getFieldValue('OP');
const list = generator.valueToCode(block, 'LIST', Order.NONE) || '{}'; const list = generator.valueToCode(block, 'LIST', Order.NONE) || '{}';
@@ -201,7 +223,9 @@ export function math_on_list(block, generator) {
// Functions needed in more than one case. // Functions needed in more than one case.
function provideSum() { function provideSum() {
return generator.provideFunction_('math_sum', ` return generator.provideFunction_(
'math_sum',
`
function ${generator.FUNCTION_NAME_PLACEHOLDER_}(t) function ${generator.FUNCTION_NAME_PLACEHOLDER_}(t)
local result = 0 local result = 0
for _, v in ipairs(t) do for _, v in ipairs(t) do
@@ -209,7 +233,8 @@ function ${generator.FUNCTION_NAME_PLACEHOLDER_}(t)
end end
return result return result
end end
`); `,
);
} }
switch (func) { switch (func) {
@@ -219,7 +244,9 @@ end
case 'MIN': case 'MIN':
// Returns 0 for the empty list. // Returns 0 for the empty list.
functionName = generator.provideFunction_('math_min', ` functionName = generator.provideFunction_(
'math_min',
`
function ${generator.FUNCTION_NAME_PLACEHOLDER_}(t) function ${generator.FUNCTION_NAME_PLACEHOLDER_}(t)
if #t == 0 then if #t == 0 then
return 0 return 0
@@ -232,24 +259,30 @@ function ${generator.FUNCTION_NAME_PLACEHOLDER_}(t)
end end
return result return result
end end
`); `,
);
break; break;
case 'AVERAGE': case 'AVERAGE':
// Returns 0 for the empty list. // Returns 0 for the empty list.
functionName = generator.provideFunction_('math_average', ` functionName = generator.provideFunction_(
'math_average',
`
function ${generator.FUNCTION_NAME_PLACEHOLDER_}(t) function ${generator.FUNCTION_NAME_PLACEHOLDER_}(t)
if #t == 0 then if #t == 0 then
return 0 return 0
end end
return ${provideSum()}(t) / #t return ${provideSum()}(t) / #t
end end
`); `,
);
break; break;
case 'MAX': case 'MAX':
// Returns 0 for the empty list. // Returns 0 for the empty list.
functionName = generator.provideFunction_('math_max', ` functionName = generator.provideFunction_(
'math_max',
`
function ${generator.FUNCTION_NAME_PLACEHOLDER_}(t) function ${generator.FUNCTION_NAME_PLACEHOLDER_}(t)
if #t == 0 then if #t == 0 then
return 0 return 0
@@ -262,12 +295,15 @@ function ${generator.FUNCTION_NAME_PLACEHOLDER_}(t)
end end
return result return result
end end
`); `,
);
break; break;
case 'MEDIAN': case 'MEDIAN':
// This operation excludes non-numbers. // This operation excludes non-numbers.
functionName = generator.provideFunction_('math_median', ` functionName = generator.provideFunction_(
'math_median',
`
function ${generator.FUNCTION_NAME_PLACEHOLDER_}(t) function ${generator.FUNCTION_NAME_PLACEHOLDER_}(t)
-- Source: http://lua-users.org/wiki/SimpleStats -- Source: http://lua-users.org/wiki/SimpleStats
if #t == 0 then if #t == 0 then
@@ -286,14 +322,17 @@ function ${generator.FUNCTION_NAME_PLACEHOLDER_}(t)
return temp[math.ceil(#temp / 2)] return temp[math.ceil(#temp / 2)]
end end
end end
`); `,
);
break; break;
case 'MODE': case 'MODE':
// 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 generator version includes non-numbers. // The generator version includes non-numbers.
functionName = generator.provideFunction_('math_modes', ` functionName = generator.provideFunction_(
'math_modes',
`
function ${generator.FUNCTION_NAME_PLACEHOLDER_}(t) function ${generator.FUNCTION_NAME_PLACEHOLDER_}(t)
-- Source: http://lua-users.org/wiki/SimpleStats -- Source: http://lua-users.org/wiki/SimpleStats
local counts = {} local counts = {}
@@ -318,11 +357,14 @@ function ${generator.FUNCTION_NAME_PLACEHOLDER_}(t)
end end
return temp return temp
end end
`); `,
);
break; break;
case 'STD_DEV': case 'STD_DEV':
functionName = generator.provideFunction_('math_standard_deviation', ` functionName = generator.provideFunction_(
'math_standard_deviation',
`
function ${generator.FUNCTION_NAME_PLACEHOLDER_}(t) function ${generator.FUNCTION_NAME_PLACEHOLDER_}(t)
local m local m
local vm local vm
@@ -340,66 +382,92 @@ function ${generator.FUNCTION_NAME_PLACEHOLDER_}(t)
result = math.sqrt(total / (count-1)) result = math.sqrt(total / (count-1))
return result return result
end end
`); `,
);
break; break;
case 'RANDOM': case 'RANDOM':
functionName = generator.provideFunction_('math_random_list', ` functionName = generator.provideFunction_(
'math_random_list',
`
function ${generator.FUNCTION_NAME_PLACEHOLDER_}(t) function ${generator.FUNCTION_NAME_PLACEHOLDER_}(t)
if #t == 0 then if #t == 0 then
return nil return nil
end end
return t[math.random(#t)] return t[math.random(#t)]
end end
`); `,
);
break; break;
default: default:
throw Error('Unknown operator: ' + func); throw Error('Unknown operator: ' + func);
} }
return [functionName + '(' + list + ')', Order.HIGH]; return [functionName + '(' + list + ')', Order.HIGH];
}; }
export function math_modulo(block, generator) { export function math_modulo(
block: Block,
generator: LuaGenerator,
): [string, Order] {
// Remainder computation. // Remainder computation.
const argument0 = const argument0 =
generator.valueToCode(block, 'DIVIDEND', Order.MULTIPLICATIVE) || '0'; generator.valueToCode(block, 'DIVIDEND', Order.MULTIPLICATIVE) || '0';
const argument1 = const argument1 =
generator.valueToCode(block, 'DIVISOR', Order.MULTIPLICATIVE) || '0'; generator.valueToCode(block, 'DIVISOR', Order.MULTIPLICATIVE) || '0';
const code = argument0 + ' % ' + argument1; const code = argument0 + ' % ' + argument1;
return [code, Order.MULTIPLICATIVE]; return [code, Order.MULTIPLICATIVE];
}; }
export function math_constrain(block, generator) { export function math_constrain(
block: Block,
generator: LuaGenerator,
): [string, Order] {
// Constrain a number between two limits. // Constrain a number between two limits.
const argument0 = generator.valueToCode(block, 'VALUE', Order.NONE) || '0'; const argument0 = generator.valueToCode(block, 'VALUE', Order.NONE) || '0';
const argument1 = const argument1 =
generator.valueToCode(block, 'LOW', Order.NONE) || '-math.huge'; generator.valueToCode(block, 'LOW', Order.NONE) || '-math.huge';
const argument2 = const argument2 =
generator.valueToCode(block, 'HIGH', Order.NONE) || 'math.huge'; generator.valueToCode(block, 'HIGH', Order.NONE) || 'math.huge';
const code = 'math.min(math.max(' + argument0 + ', ' + argument1 + '), ' + const code =
argument2 + ')'; 'math.min(math.max(' +
argument0 +
', ' +
argument1 +
'), ' +
argument2 +
')';
return [code, Order.HIGH]; return [code, Order.HIGH];
}; }
export function math_random_int(block, generator) { export function math_random_int(
block: Block,
generator: LuaGenerator,
): [string, Order] {
// Random integer between [X] and [Y]. // Random integer between [X] and [Y].
const argument0 = generator.valueToCode(block, 'FROM', Order.NONE) || '0'; const argument0 = generator.valueToCode(block, 'FROM', Order.NONE) || '0';
const argument1 = generator.valueToCode(block, 'TO', Order.NONE) || '0'; const argument1 = generator.valueToCode(block, 'TO', Order.NONE) || '0';
const code = 'math.random(' + argument0 + ', ' + argument1 + ')'; const code = 'math.random(' + argument0 + ', ' + argument1 + ')';
return [code, Order.HIGH]; return [code, Order.HIGH];
}; }
export function math_random_float(block, generator) { export function math_random_float(
block: Block,
generator: LuaGenerator,
): [string, Order] {
// Random fraction between 0 and 1. // Random fraction between 0 and 1.
return ['math.random()', Order.HIGH]; return ['math.random()', Order.HIGH];
}; }
export function math_atan2(block, generator) { export function math_atan2(
block: Block,
generator: LuaGenerator,
): [string, Order] {
// Arctangent of point (X, Y) in degrees from -180 to 180. // Arctangent of point (X, Y) in degrees from -180 to 180.
const argument0 = generator.valueToCode(block, 'X', Order.NONE) || '0'; const argument0 = generator.valueToCode(block, 'X', Order.NONE) || '0';
const argument1 = generator.valueToCode(block, 'Y', Order.NONE) || '0'; const argument1 = generator.valueToCode(block, 'Y', Order.NONE) || '0';
return [ return [
'math.deg(math.atan2(' + argument1 + ', ' + argument0 + '))', Order.HIGH 'math.deg(math.atan2(' + argument1 + ', ' + argument0 + '))',
Order.HIGH,
]; ];
}; }

View File

@@ -5,18 +5,22 @@
*/ */
/** /**
* @fileoverview Generating Lua for procedure blocks. * @file Generating Lua for procedure blocks.
*/ */
// Former goog.module ID: Blockly.Lua.procedures // Former goog.module ID: Blockly.Lua.procedures
import type {Block} from '../../core/block.js';
import type {IfReturnBlock} from '../../blocks/procedures.js';
import type {LuaGenerator} from './lua_generator.js';
import {Order} from './lua_generator.js'; import {Order} from './lua_generator.js';
export function procedures_defreturn(
export function procedures_defreturn(block, generator) { block: Block,
generator: LuaGenerator,
): null {
// Define a procedure with a return value. // Define a procedure with a return value.
const funcName = const funcName = generator.getProcedureName(block.getFieldValue('NAME'));
generator.getProcedureName(block.getFieldValue('NAME'));
let xfix1 = ''; let xfix1 = '';
if (generator.STATEMENT_PREFIX) { if (generator.STATEMENT_PREFIX) {
xfix1 += generator.injectId(generator.STATEMENT_PREFIX, block); xfix1 += generator.injectId(generator.STATEMENT_PREFIX, block);
@@ -30,8 +34,9 @@ export function procedures_defreturn(block, generator) {
let loopTrap = ''; let loopTrap = '';
if (generator.INFINITE_LOOP_TRAP) { if (generator.INFINITE_LOOP_TRAP) {
loopTrap = generator.prefixLines( loopTrap = generator.prefixLines(
generator.injectId( generator.injectId(generator.INFINITE_LOOP_TRAP, block),
generator.INFINITE_LOOP_TRAP, block), generator.INDENT); generator.INDENT,
);
} }
let branch = generator.statementToCode(block, 'STACK'); let branch = generator.statementToCode(block, 'STACK');
let returnValue = generator.valueToCode(block, 'RETURN', Order.NONE) || ''; let returnValue = generator.valueToCode(block, 'RETURN', Order.NONE) || '';
@@ -50,22 +55,36 @@ export function procedures_defreturn(block, generator) {
for (let i = 0; i < variables.length; i++) { for (let i = 0; i < variables.length; i++) {
args[i] = generator.getVariableName(variables[i]); args[i] = generator.getVariableName(variables[i]);
} }
let code = 'function ' + funcName + '(' + args.join(', ') + ')\n' + xfix1 + let code =
loopTrap + branch + xfix2 + returnValue + 'end\n'; 'function ' +
funcName +
'(' +
args.join(', ') +
')\n' +
xfix1 +
loopTrap +
branch +
xfix2 +
returnValue +
'end\n';
code = generator.scrub_(block, code); code = generator.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.
generator.definitions_['%' + funcName] = code; // TODO(#7600): find better approach than casting to any to override
// CodeGenerator declaring .definitions protected.
(generator as AnyDuringMigration).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.
export const procedures_defnoreturn = procedures_defreturn; export const procedures_defnoreturn = procedures_defreturn;
export function procedures_callreturn(block, generator) { export function procedures_callreturn(
block: Block,
generator: LuaGenerator,
): [string, Order] {
// Call a procedure with a return value. // Call a procedure with a return value.
const funcName = const funcName = generator.getProcedureName(block.getFieldValue('NAME'));
generator.getProcedureName(block.getFieldValue('NAME'));
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++) {
@@ -73,30 +92,39 @@ export function procedures_callreturn(block, generator) {
} }
const code = funcName + '(' + args.join(', ') + ')'; const code = funcName + '(' + args.join(', ') + ')';
return [code, Order.HIGH]; return [code, Order.HIGH];
}; }
export function procedures_callnoreturn(block, generator) { export function procedures_callnoreturn(
block: Block,
generator: LuaGenerator,
): string {
// 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 = generator.forBlock['procedures_callreturn'](block, generator); const tuple = generator.forBlock['procedures_callreturn'](
block,
generator,
) as [string, number];
return tuple[0] + '\n'; return tuple[0] + '\n';
}; }
export function procedures_ifreturn(block, generator) { export function procedures_ifreturn(
block: Block,
generator: LuaGenerator,
): string {
// Conditionally return value from a procedure. // Conditionally return value from a procedure.
const condition = const condition =
generator.valueToCode(block, 'CONDITION', Order.NONE) || 'false'; generator.valueToCode(block, 'CONDITION', Order.NONE) || 'false';
let code = 'if ' + condition + ' then\n'; let code = 'if ' + condition + ' then\n';
if (generator.STATEMENT_SUFFIX) { if (generator.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 += code += generator.prefixLines(
generator.prefixLines( generator.injectId(generator.STATEMENT_SUFFIX, block),
generator.injectId(generator.STATEMENT_SUFFIX, block), generator.INDENT,
generator.INDENT); );
} }
if (block.hasReturnValue_) { if ((block as IfReturnBlock).hasReturnValue_) {
const value = generator.valueToCode(block, 'VALUE', Order.NONE) || 'nil'; const value = generator.valueToCode(block, 'VALUE', Order.NONE) || 'nil';
code += generator.INDENT + 'return ' + value + '\n'; code += generator.INDENT + 'return ' + value + '\n';
} else { } else {
@@ -104,4 +132,4 @@ export function procedures_ifreturn(block, generator) {
} }
code += 'end\n'; code += 'end\n';
return code; return code;
}; }

View File

@@ -5,82 +5,99 @@
*/ */
/** /**
* @fileoverview Generating Lua for text blocks. * @file Generating Lua for text blocks.
*/ */
// Former goog.module ID: Blockly.Lua.texts // Former goog.module ID: Blockly.Lua.texts
import type {Block} from '../../core/block.js';
import type {JoinMutatorBlock} from '../../blocks/text.js';
import type {LuaGenerator} from './lua_generator.js';
import {Order} from './lua_generator.js'; import {Order} from './lua_generator.js';
export function text(block: Block, generator: LuaGenerator): [string, Order] {
export function text(block, generator) {
// Text value. // Text value.
const code = generator.quote_(block.getFieldValue('TEXT')); const code = generator.quote_(block.getFieldValue('TEXT'));
return [code, Order.ATOMIC]; return [code, Order.ATOMIC];
}; }
export function text_multiline(block, generator) { export function text_multiline(
block: Block,
generator: LuaGenerator,
): [string, Order] {
// Text value. // Text value.
const code = generator.multiline_quote_(block.getFieldValue('TEXT')); const code = generator.multiline_quote_(block.getFieldValue('TEXT'));
const order = const order = code.indexOf('..') !== -1 ? Order.CONCATENATION : Order.ATOMIC;
code.indexOf('..') !== -1 ? Order.CONCATENATION : Order.ATOMIC;
return [code, order]; return [code, order];
}; }
export function text_join(block, generator) { export function text_join(
block: Block,
generator: LuaGenerator,
): [string, Order] {
const joinBlock = block as JoinMutatorBlock;
// 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 (joinBlock.itemCount_ === 0) {
return ["''", Order.ATOMIC]; return ["''", Order.ATOMIC];
} else if (block.itemCount_ === 1) { } else if (joinBlock.itemCount_ === 1) {
const element = generator.valueToCode(block, 'ADD0', Order.NONE) || "''"; const element = generator.valueToCode(block, 'ADD0', Order.NONE) || "''";
const code = 'tostring(' + element + ')'; const code = 'tostring(' + element + ')';
return [code, Order.HIGH]; return [code, Order.HIGH];
} else if (block.itemCount_ === 2) { } else if (joinBlock.itemCount_ === 2) {
const element0 = const element0 =
generator.valueToCode(block, 'ADD0', Order.CONCATENATION) || "''"; generator.valueToCode(block, 'ADD0', Order.CONCATENATION) || "''";
const element1 = const element1 =
generator.valueToCode(block, 'ADD1', Order.CONCATENATION) || "''"; generator.valueToCode(block, 'ADD1', Order.CONCATENATION) || "''";
const code = element0 + ' .. ' + element1; const code = element0 + ' .. ' + element1;
return [code, Order.CONCATENATION]; return [code, Order.CONCATENATION];
} else { } else {
const elements = []; const elements = [];
for (let i = 0; i < block.itemCount_; i++) { for (let i = 0; i < joinBlock.itemCount_; i++) {
elements[i] = elements[i] = generator.valueToCode(block, 'ADD' + i, Order.NONE) || "''";
generator.valueToCode(block, 'ADD' + i, Order.NONE) || "''";
} }
const code = 'table.concat({' + elements.join(', ') + '})'; const code = 'table.concat({' + elements.join(', ') + '})';
return [code, Order.HIGH]; return [code, Order.HIGH];
} }
}; }
export function text_append(block, generator) { export function text_append(block: Block, generator: LuaGenerator): string {
// Append to a variable in place. // Append to a variable in place.
const varName = const varName = generator.getVariableName(block.getFieldValue('VAR'));
generator.getVariableName(block.getFieldValue('VAR'));
const value = const value =
generator.valueToCode(block, 'TEXT', Order.CONCATENATION) || "''"; generator.valueToCode(block, 'TEXT', Order.CONCATENATION) || "''";
return varName + ' = ' + varName + ' .. ' + value + '\n'; return varName + ' = ' + varName + ' .. ' + value + '\n';
}; }
export function text_length(block, generator) { export function text_length(
block: Block,
generator: LuaGenerator,
): [string, Order] {
// String or array length. // String or array length.
const text = generator.valueToCode(block, 'VALUE', Order.UNARY) || "''"; const text = generator.valueToCode(block, 'VALUE', Order.UNARY) || "''";
return ['#' + text, Order.UNARY]; return ['#' + text, Order.UNARY];
}; }
export function text_isEmpty(block, generator) { export function text_isEmpty(
block: Block,
generator: LuaGenerator,
): [string, Order] {
// Is the string null or array empty? // Is the string null or array empty?
const text = generator.valueToCode(block, 'VALUE', Order.UNARY) || "''"; const text = generator.valueToCode(block, 'VALUE', Order.UNARY) || "''";
return ['#' + text + ' == 0', Order.RELATIONAL]; return ['#' + text + ' == 0', Order.RELATIONAL];
}; }
export function text_indexOf(block, generator) { export function text_indexOf(
block: Block,
generator: LuaGenerator,
): [string, Order] {
// Search the text for a substring. // Search the text for a substring.
const substring = generator.valueToCode(block, 'FIND', Order.NONE) || "''"; const substring = generator.valueToCode(block, 'FIND', Order.NONE) || "''";
const text = generator.valueToCode(block, 'VALUE', Order.NONE) || "''"; const text = generator.valueToCode(block, 'VALUE', Order.NONE) || "''";
let functionName; let functionName;
if (block.getFieldValue('END') === 'FIRST') { if (block.getFieldValue('END') === 'FIRST') {
functionName = generator.provideFunction_('firstIndexOf', ` functionName = generator.provideFunction_(
'firstIndexOf',
`
function ${generator.FUNCTION_NAME_PLACEHOLDER_}(str, substr) function ${generator.FUNCTION_NAME_PLACEHOLDER_}(str, substr)
local i = string.find(str, substr, 1, true) local i = string.find(str, substr, 1, true)
if i == nil then if i == nil then
@@ -88,9 +105,12 @@ function ${generator.FUNCTION_NAME_PLACEHOLDER_}(str, substr)
end end
return i return i
end end
`); `,
);
} else { } else {
functionName = generator.provideFunction_('lastIndexOf', ` functionName = generator.provideFunction_(
'lastIndexOf',
`
function ${generator.FUNCTION_NAME_PLACEHOLDER_}(str, substr) function ${generator.FUNCTION_NAME_PLACEHOLDER_}(str, substr)
local i = string.find(string.reverse(str), string.reverse(substr), 1, true) local i = string.find(string.reverse(str), string.reverse(substr), 1, true)
if i then if i then
@@ -98,27 +118,34 @@ function ${generator.FUNCTION_NAME_PLACEHOLDER_}(str, substr)
end end
return 0 return 0
end end
`); `,
);
} }
const code = functionName + '(' + text + ', ' + substring + ')'; const code = functionName + '(' + text + ', ' + substring + ')';
return [code, Order.HIGH]; return [code, Order.HIGH];
}; }
export function text_charAt(block, generator) { export function text_charAt(
block: Block,
generator: LuaGenerator,
): [string, Order] {
// 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') ? Order.UNARY : Order.NONE; const atOrder = where === 'FROM_END' ? Order.UNARY : Order.NONE;
const at = generator.valueToCode(block, 'AT', atOrder) || '1'; const at = generator.valueToCode(block, 'AT', atOrder) || '1';
const text = generator.valueToCode(block, 'VALUE', Order.NONE) || "''"; const text = generator.valueToCode(block, 'VALUE', Order.NONE) || "''";
let code; let code;
if (where === 'RANDOM') { if (where === 'RANDOM') {
const functionName = generator.provideFunction_('text_random_letter', ` const functionName = generator.provideFunction_(
'text_random_letter',
`
function ${generator.FUNCTION_NAME_PLACEHOLDER_}(str) function ${generator.FUNCTION_NAME_PLACEHOLDER_}(str)
local index = math.random(string.len(str)) local index = math.random(string.len(str))
return string.sub(str, index, index) return string.sub(str, index, index)
end end
`); `,
);
code = functionName + '(' + text + ')'; code = functionName + '(' + text + ')';
} else { } else {
let start; let start;
@@ -139,24 +166,30 @@ end
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 = generator.provideFunction_('text_char_at', ` const functionName = generator.provideFunction_(
'text_char_at',
`
function ${generator.FUNCTION_NAME_PLACEHOLDER_}(str, index) function ${generator.FUNCTION_NAME_PLACEHOLDER_}(str, index)
return string.sub(str, index, index) return string.sub(str, index, index)
end end
`); `,
);
code = functionName + '(' + text + ', ' + start + ')'; code = functionName + '(' + text + ', ' + start + ')';
} }
} }
return [code, Order.HIGH]; return [code, Order.HIGH];
}; }
export function text_getSubstring(block, generator) { export function text_getSubstring(
block: Block,
generator: LuaGenerator,
): [string, Order] {
// Get substring. // Get substring.
const text = generator.valueToCode(block, 'STRING', Order.NONE) || "''"; const text = generator.valueToCode(block, 'STRING', Order.NONE) || "''";
// Get start index. // Get start index.
const where1 = block.getFieldValue('WHERE1'); const where1 = block.getFieldValue('WHERE1');
const at1Order = (where1 === 'FROM_END') ? Order.UNARY : Order.NONE; const at1Order = where1 === 'FROM_END' ? Order.UNARY : Order.NONE;
const at1 = generator.valueToCode(block, 'AT1', at1Order) || '1'; const at1 = generator.valueToCode(block, 'AT1', at1Order) || '1';
let start; let start;
if (where1 === 'FIRST') { if (where1 === 'FIRST') {
@@ -171,7 +204,7 @@ export function text_getSubstring(block, generator) {
// Get end index. // Get end index.
const where2 = block.getFieldValue('WHERE2'); const where2 = block.getFieldValue('WHERE2');
const at2Order = (where2 === 'FROM_END') ? Order.UNARY : Order.NONE; const at2Order = where2 === 'FROM_END' ? Order.UNARY : Order.NONE;
const at2 = generator.valueToCode(block, 'AT2', at2Order) || '1'; const at2 = generator.valueToCode(block, 'AT2', at2Order) || '1';
let end; let end;
if (where2 === 'LAST') { if (where2 === 'LAST') {
@@ -185,9 +218,12 @@ export function text_getSubstring(block, generator) {
} }
const code = 'string.sub(' + text + ', ' + start + ', ' + end + ')'; const code = 'string.sub(' + text + ', ' + start + ', ' + end + ')';
return [code, Order.HIGH]; return [code, Order.HIGH];
}; }
export function text_changeCase(block, generator) { export function text_changeCase(
block: Block,
generator: LuaGenerator,
): [string, Order] {
// Change capitalization. // Change capitalization.
const operator = block.getFieldValue('CASE'); const operator = block.getFieldValue('CASE');
const text = generator.valueToCode(block, 'TEXT', Order.NONE) || "''"; const text = generator.valueToCode(block, 'TEXT', Order.NONE) || "''";
@@ -200,7 +236,9 @@ export function text_changeCase(block, generator) {
// 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.
functionName = generator.provideFunction_('text_titlecase', ` functionName = generator.provideFunction_(
'text_titlecase',
`
function ${generator.FUNCTION_NAME_PLACEHOLDER_}(str) function ${generator.FUNCTION_NAME_PLACEHOLDER_}(str)
local buf = {} local buf = {}
local inWord = false local inWord = false
@@ -218,28 +256,36 @@ function ${generator.FUNCTION_NAME_PLACEHOLDER_}(str)
end end
return table.concat(buf) return table.concat(buf)
end end
`); `,
);
} }
const code = functionName + '(' + text + ')'; const code = functionName + '(' + text + ')';
return [code, Order.HIGH]; return [code, Order.HIGH];
}; }
export function text_trim(block, generator) { export function text_trim(
block: Block,
generator: LuaGenerator,
): [string, Order] {
// Trim spaces. // Trim spaces.
const OPERATORS = {LEFT: '^%s*(,-)', RIGHT: '(.-)%s*$', BOTH: '^%s*(.-)%s*$'}; const OPERATORS = {LEFT: '^%s*(,-)', RIGHT: '(.-)%s*$', BOTH: '^%s*(.-)%s*$'};
const operator = OPERATORS[block.getFieldValue('MODE')]; type OperatorOption = keyof typeof OPERATORS;
const operator = OPERATORS[block.getFieldValue('MODE') as OperatorOption];
const text = generator.valueToCode(block, 'TEXT', Order.NONE) || "''"; const text = generator.valueToCode(block, 'TEXT', Order.NONE) || "''";
const code = 'string.gsub(' + text + ', "' + operator + '", "%1")'; const code = 'string.gsub(' + text + ', "' + operator + '", "%1")';
return [code, Order.HIGH]; return [code, Order.HIGH];
}; }
export function text_print(block, generator) { export function text_print(block: Block, generator: LuaGenerator): string {
// Print statement. // Print statement.
const msg = generator.valueToCode(block, 'TEXT', Order.NONE) || "''"; const msg = generator.valueToCode(block, 'TEXT', Order.NONE) || "''";
return 'print(' + msg + ')\n'; return 'print(' + msg + ')\n';
}; }
export function text_prompt_ext(block, generator) { export function text_prompt_ext(
block: Block,
generator: LuaGenerator,
): [string, Order] {
// Prompt function. // Prompt function.
let msg; let msg;
if (block.getField('TEXT')) { if (block.getField('TEXT')) {
@@ -250,13 +296,16 @@ export function text_prompt_ext(block, generator) {
msg = generator.valueToCode(block, 'TEXT', Order.NONE) || "''"; msg = generator.valueToCode(block, 'TEXT', Order.NONE) || "''";
} }
const functionName = generator.provideFunction_('text_prompt', ` const functionName = generator.provideFunction_(
'text_prompt',
`
function ${generator.FUNCTION_NAME_PLACEHOLDER_}(msg) function ${generator.FUNCTION_NAME_PLACEHOLDER_}(msg)
io.write(msg) io.write(msg)
io.flush() io.flush()
return io.read() return io.read()
end end
`); `,
);
let code = functionName + '(' + msg + ')'; let code = functionName + '(' + msg + ')';
const toNumber = block.getFieldValue('TYPE') === 'NUMBER'; const toNumber = block.getFieldValue('TYPE') === 'NUMBER';
@@ -264,14 +313,19 @@ end
code = 'tonumber(' + code + ', 10)'; code = 'tonumber(' + code + ', 10)';
} }
return [code, Order.HIGH]; return [code, Order.HIGH];
}; }
export const text_prompt = text_prompt_ext; export const text_prompt = text_prompt_ext;
export function text_count(block, generator) { export function text_count(
block: Block,
generator: LuaGenerator,
): [string, Order] {
const text = generator.valueToCode(block, 'TEXT', Order.NONE) || "''"; const text = generator.valueToCode(block, 'TEXT', Order.NONE) || "''";
const sub = generator.valueToCode(block, 'SUB', Order.NONE) || "''"; const sub = generator.valueToCode(block, 'SUB', Order.NONE) || "''";
const functionName = generator.provideFunction_('text_count', ` const functionName = generator.provideFunction_(
'text_count',
`
function ${generator.FUNCTION_NAME_PLACEHOLDER_}(haystack, needle) function ${generator.FUNCTION_NAME_PLACEHOLDER_}(haystack, needle)
if #needle == 0 then if #needle == 0 then
return #haystack + 1 return #haystack + 1
@@ -288,16 +342,22 @@ function ${generator.FUNCTION_NAME_PLACEHOLDER_}(haystack, needle)
end end
return count return count
end end
`); `,
);
const code = functionName + '(' + text + ', ' + sub + ')'; const code = functionName + '(' + text + ', ' + sub + ')';
return [code, Order.HIGH]; return [code, Order.HIGH];
}; }
export function text_replace(block, generator) { export function text_replace(
block: Block,
generator: LuaGenerator,
): [string, Order] {
const text = generator.valueToCode(block, 'TEXT', Order.NONE) || "''"; const text = generator.valueToCode(block, 'TEXT', Order.NONE) || "''";
const from = generator.valueToCode(block, 'FROM', Order.NONE) || "''"; const from = generator.valueToCode(block, 'FROM', Order.NONE) || "''";
const to = generator.valueToCode(block, 'TO', Order.NONE) || "''"; const to = generator.valueToCode(block, 'TO', Order.NONE) || "''";
const functionName = generator.provideFunction_('text_replace', ` const functionName = generator.provideFunction_(
'text_replace',
`
function ${generator.FUNCTION_NAME_PLACEHOLDER_}(haystack, needle, replacement) function ${generator.FUNCTION_NAME_PLACEHOLDER_}(haystack, needle, replacement)
local buf = {} local buf = {}
local i = 1 local i = 1
@@ -314,13 +374,17 @@ function ${generator.FUNCTION_NAME_PLACEHOLDER_}(haystack, needle, replacement)
end end
return table.concat(buf) return table.concat(buf)
end end
`); `,
);
const code = functionName + '(' + text + ', ' + from + ', ' + to + ')'; const code = functionName + '(' + text + ', ' + from + ', ' + to + ')';
return [code, Order.HIGH]; return [code, Order.HIGH];
}; }
export function text_reverse(block, generator) { export function text_reverse(
block: Block,
generator: LuaGenerator,
): [string, Order] {
const text = generator.valueToCode(block, 'TEXT', Order.NONE) || "''"; const text = generator.valueToCode(block, 'TEXT', Order.NONE) || "''";
const code = 'string.reverse(' + text + ')'; const code = 'string.reverse(' + text + ')';
return [code, Order.HIGH]; return [code, Order.HIGH];
}; }

View File

@@ -1,29 +0,0 @@
/**
* @license
* Copyright 2016 Google LLC
* SPDX-License-Identifier: Apache-2.0
*/
/**
* @fileoverview Generating Lua for variable blocks.
*/
// Former goog.module ID: Blockly.Lua.variables
import {Order} from './lua_generator.js';
export function variables_get(block, generator) {
// Variable getter.
const code =
generator.getVariableName(block.getFieldValue('VAR'));
return [code, Order.ATOMIC];
};
export function variables_set(block, generator) {
// Variable setter.
const argument0 = generator.valueToCode(block, 'VALUE', Order.NONE) || '0';
const varName =
generator.getVariableName(block.getFieldValue('VAR'));
return varName + ' = ' + argument0 + '\n';
};

View File

@@ -0,0 +1,31 @@
/**
* @license
* Copyright 2016 Google LLC
* SPDX-License-Identifier: Apache-2.0
*/
/**
* @file Generating Lua for variable blocks.
*/
// Former goog.module ID: Blockly.Lua.variables
import type {Block} from '../../core/block.js';
import type {LuaGenerator} from './lua_generator.js';
import {Order} from './lua_generator.js';
export function variables_get(
block: Block,
generator: LuaGenerator,
): [string, Order] {
// Variable getter.
const code = generator.getVariableName(block.getFieldValue('VAR'));
return [code, Order.ATOMIC];
}
export function variables_set(block: Block, generator: LuaGenerator): string {
// Variable setter.
const argument0 = generator.valueToCode(block, 'VALUE', Order.NONE) || '0';
const varName = generator.getVariableName(block.getFieldValue('VAR'));
return varName + ' = ' + argument0 + '\n';
}

View File

@@ -5,12 +5,11 @@
*/ */
/** /**
* @fileoverview Generating Lua for dynamic variable blocks. * @file Generating Lua for dynamic variable blocks.
*/ */
// Former goog.module ID: Blockly.Lua.variablesDynamic // Former goog.module ID: Blockly.Lua.variablesDynamic
// Lua is dynamically typed. // Lua is dynamically typed.
export { export {
variables_get as variables_get_dynamic, variables_get as variables_get_dynamic,