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.
* @suppress {extraRequire}
*/
// Former goog.module ID: Blockly.Lua.all
@@ -27,13 +26,21 @@ export * from './lua/lua_generator.js';
/**
* Lua code generator instance.
* @type {!LuaGenerator}
*/
export const luaGenerator = new LuaGenerator();
// Install per-block-type generator functions:
Object.assign(
luaGenerator.forBlock,
colour, lists, logic, loops, math, procedures,
text, variables, variablesDynamic
);
const generators: typeof luaGenerator.forBlock = {
...colour,
...lists,
...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
import type {Block} from '../../core/block.js';
import type {LuaGenerator} from './lua_generator.js';
import {Order} from './lua_generator.js';
export function colour_picker(block, generator) {
export function colour_picker(
block: Block,
generator: LuaGenerator,
): [string, Order] {
// Colour picker.
const code = generator.quote_(block.getFieldValue('COLOUR'));
return [code, Order.ATOMIC];
};
}
export function colour_random(block, generator) {
export function colour_random(
block: Block,
generator: LuaGenerator,
): [string, Order] {
// Generate a random colour.
const code = 'string.format("#%06x", math.random(0, 2^24 - 1))';
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.
const functionName = generator.provideFunction_('colour_rgb', `
const functionName = generator.provideFunction_(
'colour_rgb',
`
function ${generator.FUNCTION_NAME_PLACEHOLDER_}(r, g, b)
r = math.floor(math.min(100, math.max(0, r)) * 2.55 + .5)
g = math.floor(math.min(100, math.max(0, g)) * 2.55 + .5)
b = math.floor(math.min(100, math.max(0, b)) * 2.55 + .5)
return string.format("#%02x%02x%02x", r, g, b)
end
`);
`,
);
const r = generator.valueToCode(block, 'RED', Order.NONE) || 0;
const g = generator.valueToCode(block, 'GREEN', Order.NONE) || 0;
const b = generator.valueToCode(block, 'BLUE', Order.NONE) || 0;
const code = functionName + '(' + r + ', ' + g + ', ' + b + ')';
return [code, Order.HIGH];
};
}
export function colour_blend(block, generator) {
export function colour_blend(
block: Block,
generator: LuaGenerator,
): [string, Order] {
// Blend two colours together.
const functionName = generator.provideFunction_('colour_blend', `
const functionName = generator.provideFunction_(
'colour_blend',
`
function ${generator.FUNCTION_NAME_PLACEHOLDER_}(colour1, colour2, ratio)
local r1 = tonumber(string.sub(colour1, 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)
return string.format("#%02x%02x%02x", r, g, b)
end
`);
`,
);
const colour1 =
generator.valueToCode(block, 'COLOUR1', Order.NONE) || "'#000000'";
generator.valueToCode(block, 'COLOUR1', Order.NONE) || "'#000000'";
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 code =
functionName + '(' + colour1 + ', ' + colour2 + ', ' + ratio + ')';
functionName + '(' + colour1 + ', ' + colour2 + ', ' + ratio + ')';
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
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 {Order} from './lua_generator.js';
export function lists_create_empty(block, generator) {
export function lists_create_empty(
block: Block,
generator: LuaGenerator,
): [string, Order] {
// Create an empty list.
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.
const elements = new Array(block.itemCount_);
for (let i = 0; i < block.itemCount_; i++) {
const elements = new Array(createWithBlock.itemCount_);
for (let i = 0; i < createWithBlock.itemCount_; i++) {
elements[i] =
generator.valueToCode(block, 'ADD' + i, Order.NONE) || 'None';
generator.valueToCode(createWithBlock, 'ADD' + i, Order.NONE) || 'None';
}
const code = '{' + elements.join(', ') + '}';
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.
const functionName = generator.provideFunction_('create_list_repeated', `
const functionName = generator.provideFunction_(
'create_list_repeated',
`
function ${generator.FUNCTION_NAME_PLACEHOLDER_}(item, count)
local t = {}
for i = 1, count do
@@ -40,33 +54,45 @@ function ${generator.FUNCTION_NAME_PLACEHOLDER_}(item, count)
end
return t
end
`);
`,
);
const element = generator.valueToCode(block, 'ITEM', Order.NONE) || 'None';
const repeatCount = generator.valueToCode(block, 'NUM', Order.NONE) || '0';
const code = functionName + '(' + element + ', ' + repeatCount + ')';
return [code, Order.HIGH];
};
}
export function lists_length(block, generator) {
export function lists_length(
block: Block,
generator: LuaGenerator,
): [string, Order] {
// String or array length.
const list = generator.valueToCode(block, 'VALUE', 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?
const list = generator.valueToCode(block, 'VALUE', Order.UNARY) || '{}';
const code = '#' + list + ' == 0';
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.
const item = generator.valueToCode(block, 'FIND', Order.NONE) || "''";
const list = generator.valueToCode(block, 'VALUE', Order.NONE) || '{}';
let functionName;
if (block.getFieldValue('END') === 'FIRST') {
functionName = generator.provideFunction_('first_index', `
functionName = generator.provideFunction_(
'first_index',
`
function ${generator.FUNCTION_NAME_PLACEHOLDER_}(t, elem)
for k, v in ipairs(t) do
if v == elem then
@@ -75,9 +101,12 @@ function ${generator.FUNCTION_NAME_PLACEHOLDER_}(t, elem)
end
return 0
end
`);
`,
);
} else {
functionName = generator.provideFunction_('last_index', `
functionName = generator.provideFunction_(
'last_index',
`
function ${generator.FUNCTION_NAME_PLACEHOLDER_}(t, elem)
for i = #t, 1, -1 do
if t[i] == elem then
@@ -86,20 +115,26 @@ function ${generator.FUNCTION_NAME_PLACEHOLDER_}(t, elem)
end
return 0
end
`);
`,
);
}
const code = functionName + '(' + list + ', ' + item + ')';
return [code, Order.HIGH];
};
}
/**
* 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 {string=} opt_at The optional offset when indexing from start/end.
* @return {string|undefined} Index expression.
*
* @param listName Name of the list, used to calculate length.
* @param where The method of indexing, selected by dropdown in Blockly
* @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') {
return '1';
} 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.
// Note: Until January 2013 this block did not have MODE or WHERE inputs.
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,
// FROM_END, and RANDOM) and is non-trivial, make sure to access it only once.
if ((where === 'LAST' || where === 'FROM_END' || where === 'RANDOM') &&
!list.match(/^\w+$/)) {
if (
(where === 'LAST' || where === 'FROM_END' || where === 'RANDOM') &&
!list.match(/^\w+$/)
) {
// `list` is an expression, so we may not evaluate it more than once.
if (mode === 'REMOVE') {
// We can use multiple statements.
const atOrder =
(where === 'FROM_END') ? Order.ADDITIVE : Order.NONE;
const atOrder = where === 'FROM_END' ? Order.ADDITIVE : Order.NONE;
let at = generator.valueToCode(block, 'AT', atOrder) || '1';
const listVar =
generator.nameDB_.getDistinctName('tmp_list', NameType.VARIABLE);
const listVar = generator.nameDB_!.getDistinctName(
'tmp_list',
NameType.VARIABLE,
);
at = getListIndex(listVar, where, at);
const code = listVar + ' = ' + list + '\n' +
'table.remove(' + listVar + ', ' + at + ')\n';
const code =
listVar +
' = ' +
list +
'\n' +
'table.remove(' +
listVar +
', ' +
at +
')\n';
return code;
} else {
// We need to create a procedure to avoid reevaluating values.
@@ -142,41 +191,49 @@ export function lists_getIndex(block, generator) {
let functionName;
if (mode === 'GET') {
functionName = generator.provideFunction_(
'list_get_' + where.toLowerCase(), [
'function ' + generator.FUNCTION_NAME_PLACEHOLDER_ + '(t' +
'list_get_' + where.toLowerCase(),
[
'function ' +
generator.FUNCTION_NAME_PLACEHOLDER_ +
'(t' +
// The value for 'FROM_END' and'FROM_START' depends on `at` so
// we add it as a parameter.
((where === 'FROM_END' || where === 'FROM_START') ? ', at)' :
')'),
' return t[' + getListIndex('t', where, 'at') + ']', 'end'
]);
} else { // `mode` === 'GET_REMOVE'
functionName =
generator.provideFunction_(
'list_remove_' + where.toLowerCase(), [
'function ' + generator.FUNCTION_NAME_PLACEHOLDER_ + '(t' +
// The value for 'FROM_END' and'FROM_START' depends on `at` so
// we add it as a parameter.
((where === 'FROM_END' || where === 'FROM_START') ? ', at)' :
')'),
' return table.remove(t, ' + getListIndex('t', where, 'at') +
')',
'end'
]);
(where === 'FROM_END' || where === 'FROM_START' ? ', at)' : ')'),
' return t[' + getListIndex('t', where, 'at') + ']',
'end',
],
);
} else {
// `mode` === 'GET_REMOVE'
functionName = generator.provideFunction_(
'list_remove_' + where.toLowerCase(),
[
'function ' +
generator.FUNCTION_NAME_PLACEHOLDER_ +
'(t' +
// The value for 'FROM_END' and'FROM_START' depends on `at` so
// we add it as a parameter.
(where === 'FROM_END' || where === 'FROM_START' ? ', at)' : ')'),
' return table.remove(t, ' + getListIndex('t', where, 'at') + ')',
'end',
],
);
}
const code = functionName + '(' + list +
// The value for 'FROM_END' and 'FROM_START' depends on `at` so we
// pass it.
((where === 'FROM_END' || where === 'FROM_START') ? ', ' + at : '') +
')';
const code =
functionName +
'(' +
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];
}
} else {
// Either `list` is a simple variable, or we only need to refer to `list`
// once.
const atOrder = (mode === 'GET' && where === 'FROM_END') ?
Order.ADDITIVE :
Order.NONE;
const atOrder =
mode === 'GET' && where === 'FROM_END' ? Order.ADDITIVE : Order.NONE;
let at = generator.valueToCode(block, 'AT', atOrder) || '1';
at = getListIndex(list, where, at);
if (mode === 'GET') {
@@ -186,14 +243,15 @@ export function lists_getIndex(block, generator) {
const code = 'table.remove(' + list + ', ' + at + ')';
if (mode === 'GET_REMOVE') {
return [code, Order.HIGH];
} else { // `mode` === 'REMOVE'
} else {
// `mode` === 'REMOVE'
return code + '\n';
}
}
}
};
}
export function lists_setIndex(block, generator) {
export function lists_setIndex(block: Block, generator: LuaGenerator): string {
// Set element at index.
// Note: Until February 2013 this block did not have MODE or WHERE inputs.
let list = generator.valueToCode(block, 'LIST', Order.HIGH) || '{}';
@@ -205,28 +263,41 @@ export function lists_setIndex(block, generator) {
let code = '';
// 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.
if ((where === 'LAST' || where === 'FROM_END' || where === 'RANDOM') &&
!list.match(/^\w+$/)) {
if (
(where === 'LAST' || where === 'FROM_END' || where === 'RANDOM') &&
!list.match(/^\w+$/)
) {
// `list` is an expression, so we may not evaluate it more than once.
// We can use multiple statements.
const listVar =
generator.nameDB_.getDistinctName('tmp_list', NameType.VARIABLE);
const listVar = generator.nameDB_!.getDistinctName(
'tmp_list',
NameType.VARIABLE,
);
code = listVar + ' = ' + list + '\n';
list = listVar;
}
if (mode === 'SET') {
code += list + '[' + getListIndex(list, where, at) + '] = ' + value;
} else { // `mode` === 'INSERT'
} else {
// `mode` === 'INSERT'
// LAST is a special case, because we want to insert
// *after* not *before*, the existing last element.
code += 'table.insert(' + list + ', ' +
(getListIndex(list, where, at) + (where === 'LAST' ? ' + 1' : '')) +
', ' + value + ')';
code +=
'table.insert(' +
list +
', ' +
(getListIndex(list, where, at) + (where === 'LAST' ? ' + 1' : '')) +
', ' +
value +
')';
}
return code + '\n';
};
}
export function lists_getSublist(block, generator) {
export function lists_getSublist(
block: Block,
generator: LuaGenerator,
): [string, Order] {
// Get sublist.
const list = generator.valueToCode(block, 'LIST', Order.NONE) || '{}';
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
// we add it as a parameter.
const at1Param =
(where1 === 'FROM_END' || where1 === 'FROM_START') ? ', at1' : '';
where1 === 'FROM_END' || where1 === 'FROM_START' ? ', at1' : '';
const at2Param =
(where2 === 'FROM_END' || where2 === 'FROM_START') ? ', at2' : '';
where2 === 'FROM_END' || where2 === 'FROM_START' ? ', at2' : '';
const functionName = generator.provideFunction_(
'list_sublist_' + where1.toLowerCase() + '_' + where2.toLowerCase(), `
'list_sublist_' + where1.toLowerCase() + '_' + where2.toLowerCase(),
`
function ${generator.FUNCTION_NAME_PLACEHOLDER_}(source${at1Param}${at2Param})
local t = {}
local start = ${getListIndex('source', where1, 'at1')}
@@ -251,23 +323,32 @@ function ${generator.FUNCTION_NAME_PLACEHOLDER_}(source${at1Param}${at2Param})
end
return t
end
`);
const code = functionName + '(' + 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 : '') +
')';
`,
);
const code =
functionName +
'(' +
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];
};
}
export function lists_sort(block, generator) {
export function lists_sort(
block: Block,
generator: LuaGenerator,
): [string, Order] {
// Block for sorting a list.
const list = generator.valueToCode(block, 'LIST', Order.NONE) || '{}';
const direction = block.getFieldValue('DIRECTION') === '1' ? 1 : -1;
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)
local t = {}
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)
return t
end
`);
`,
);
const code =
functionName + '(' + list + ',"' + type + '", ' + direction + ')';
functionName + '(' + list + ',"' + type + '", ' + direction + ')';
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.
let input = generator.valueToCode(block, 'INPUT', Order.NONE);
const delimiter =
generator.valueToCode(block, 'DELIM', Order.NONE) || "''";
const delimiter = generator.valueToCode(block, 'DELIM', Order.NONE) || "''";
const mode = block.getFieldValue('MODE');
let functionName;
if (mode === 'SPLIT') {
if (!input) {
input = "''";
}
functionName = generator.provideFunction_('list_string_split', `
functionName = generator.provideFunction_(
'list_string_split',
`
function ${generator.FUNCTION_NAME_PLACEHOLDER_}(input, delim)
local t = {}
local pos = 1
@@ -322,7 +408,8 @@ function ${generator.FUNCTION_NAME_PLACEHOLDER_}(input, delim)
end
return t
end
`);
`,
);
} else if (mode === 'JOIN') {
if (!input) {
input = '{}';
@@ -333,12 +420,17 @@ end
}
const code = functionName + '(' + input + ', ' + delimiter + ')';
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.
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)
local reversed = {}
for i = #input, 1, -1 do
@@ -346,7 +438,8 @@ function ${generator.FUNCTION_NAME_PLACEHOLDER_}(input)
end
return reversed
end
`);
`,
);
const code = functionName + '(' + list + ')';
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
import type {Block} from '../../core/block.js';
import type {LuaGenerator} from './lua_generator.js';
import {Order} from './lua_generator.js';
export function controls_if(block, generator) {
export function controls_if(block: Block, generator: LuaGenerator): string {
// If/elseif/else condition.
let n = 0;
let code = '';
@@ -23,15 +24,17 @@ export function controls_if(block, generator) {
}
do {
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);
if (generator.STATEMENT_SUFFIX) {
branchCode = generator.prefixLines(
branchCode =
generator.prefixLines(
generator.injectId(generator.STATEMENT_SUFFIX, block),
generator.INDENT) + branchCode;
generator.INDENT,
) + branchCode;
}
code +=
(n > 0 ? 'else' : '') + 'if ' + conditionCode + ' then\n' + branchCode;
(n > 0 ? 'else' : '') + 'if ' + conditionCode + ' then\n' + branchCode;
n++;
} while (block.getInput('IF' + n));
@@ -39,36 +42,46 @@ export function controls_if(block, generator) {
let branchCode = generator.statementToCode(block, 'ELSE');
if (generator.STATEMENT_SUFFIX) {
branchCode =
generator.prefixLines(
generator.injectId(
generator.STATEMENT_SUFFIX, block),
generator.INDENT) +
branchCode;
generator.prefixLines(
generator.injectId(generator.STATEMENT_SUFFIX, block),
generator.INDENT,
) + branchCode;
}
code += 'else\n' + branchCode;
}
return code + 'end\n';
};
}
export const controls_ifelse = controls_if;
export function logic_compare(block, generator) {
export function logic_compare(
block: Block,
generator: LuaGenerator,
): [string, Order] {
// Comparison operator.
const OPERATORS =
{'EQ': '==', 'NEQ': '~=', 'LT': '<', 'LTE': '<=', 'GT': '>', 'GTE': '>='};
const operator = OPERATORS[block.getFieldValue('OP')];
const argument0 =
generator.valueToCode(block, 'A', Order.RELATIONAL) || '0';
const argument1 =
generator.valueToCode(block, 'B', Order.RELATIONAL) || '0';
const OPERATORS = {
'EQ': '==',
'NEQ': '~=',
'LT': '<',
'LTE': '<=',
'GT': '>',
'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;
return [code, Order.RELATIONAL];
};
}
export function logic_operation(block, generator) {
export function logic_operation(
block: Block,
generator: LuaGenerator,
): [string, Order] {
// Operations 'and', 'or'.
const operator = (block.getFieldValue('OP') === 'AND') ? 'and' : 'or';
const order = (operator === 'and') ? Order.AND : Order.OR;
const operator = block.getFieldValue('OP') === 'AND' ? 'and' : 'or';
const order = operator === 'and' ? Order.AND : Order.OR;
let argument0 = generator.valueToCode(block, 'A', order);
let argument1 = generator.valueToCode(block, 'B', order);
if (!argument0 && !argument1) {
@@ -77,7 +90,7 @@ export function logic_operation(block, generator) {
argument1 = 'false';
} else {
// Single missing arguments have no effect on the return value.
const defaultArgument = (operator === 'and') ? 'true' : 'false';
const defaultArgument = operator === 'and' ? 'true' : 'false';
if (!argument0) {
argument0 = defaultArgument;
}
@@ -87,33 +100,43 @@ export function logic_operation(block, generator) {
}
const code = argument0 + ' ' + operator + ' ' + argument1;
return [code, order];
};
}
export function logic_negate(block, generator) {
export function logic_negate(
block: Block,
generator: LuaGenerator,
): [string, Order] {
// Negation.
const argument0 =
generator.valueToCode(block, 'BOOL', Order.UNARY) || 'true';
const argument0 = generator.valueToCode(block, 'BOOL', Order.UNARY) || 'true';
const code = 'not ' + argument0;
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.
const code = (block.getFieldValue('BOOL') === 'TRUE') ? 'true' : 'false';
const code = block.getFieldValue('BOOL') === 'TRUE' ? 'true' : 'false';
return [code, Order.ATOMIC];
};
}
export function logic_null(block, generator) {
export function logic_null(
block: Block,
generator: LuaGenerator,
): [string, Order] {
// Null data type.
return ['nil', Order.ATOMIC];
};
}
export function logic_ternary(block, generator) {
export function logic_ternary(
block: Block,
generator: LuaGenerator,
): [string, Order] {
// Ternary operator.
const value_if = generator.valueToCode(block, 'IF', Order.AND) || 'false';
const value_then =
generator.valueToCode(block, 'THEN', Order.AND) || 'nil';
const value_then = generator.valueToCode(block, 'THEN', Order.AND) || 'nil';
const value_else = generator.valueToCode(block, 'ELSE', Order.OR) || 'nil';
const code = value_if + ' and ' + value_then + ' or ' + value_else;
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
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 {Order} from './lua_generator.js';
/**
* 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
* the appropriate label can be put at the end of the loop body.
* @const {string}
*/
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
* blockToCode.
*
* @param {string} branch Generated code of the loop body
* @param {string} indent Whitespace by which to indent a continue statement.
* @return {string} Generated label or '' if unnecessary
* @param branch Generated code of the loop body
* @param indent Whitespace by which to indent a continue statement.
* @returns Generated label or '' if unnecessary
*/
function addContinueLabel(branch, indent) {
function addContinueLabel(branch: string, indent: string): string {
if (branch.indexOf(CONTINUE_STATEMENT) !== -1) {
// False positives are possible (e.g. a string literal), but are harmless.
return branch + indent + '::continue::\n';
} else {
return branch;
}
};
}
export function controls_repeat_ext(block, generator) {
export function controls_repeat_ext(
block: Block,
generator: LuaGenerator,
): string {
// Repeat n times.
let repeats;
if (block.getField('TIMES')) {
@@ -60,21 +64,26 @@ export function controls_repeat_ext(block, generator) {
let branch = generator.statementToCode(block, 'DO');
branch = generator.addLoopTrap(branch, block);
branch = addContinueLabel(branch, generator.INDENT);
const loopVar = generator.nameDB_.getDistinctName('count', NameType.VARIABLE);
const loopVar = generator.nameDB_!.getDistinctName(
'count',
NameType.VARIABLE,
);
const code =
'for ' + loopVar + ' = 1, ' + repeats + ' do\n' + branch + 'end\n';
'for ' + loopVar + ' = 1, ' + repeats + ' do\n' + branch + 'end\n';
return code;
};
}
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.
const until = block.getFieldValue('MODE') === 'UNTIL';
let argument0 =
generator.valueToCode(
block, 'BOOL', until ? Order.UNARY : Order.NONE) ||
'false';
generator.valueToCode(block, 'BOOL', until ? Order.UNARY : Order.NONE) ||
'false';
let branch = generator.statementToCode(block, 'DO');
branch = generator.addLoopTrap(branch, block);
branch = addContinueLabel(branch, generator.INDENT);
@@ -82,12 +91,11 @@ export function controls_whileUntil(block, generator) {
argument0 = 'not ' + argument0;
}
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.
const variable0 =
generator.getVariableName(block.getFieldValue('VAR'));
const variable0 = generator.getVariableName(block.getFieldValue('VAR'));
const startVar = generator.valueToCode(block, 'FROM', Order.NONE) || '0';
const endVar = generator.valueToCode(block, 'TO', Order.NONE) || '0';
const increment = generator.valueToCode(block, 'BY', Order.NONE) || '1';
@@ -96,8 +104,11 @@ export function controls_for(block, generator) {
branch = addContinueLabel(branch, generator.INDENT);
let code = '';
let incValue;
if (stringUtils.isNumber(startVar) && stringUtils.isNumber(endVar) &&
stringUtils.isNumber(increment)) {
if (
stringUtils.isNumber(startVar) &&
stringUtils.isNumber(endVar) &&
stringUtils.isNumber(increment)
) {
// All arguments are simple numbers.
const up = Number(startVar) <= Number(endVar);
const step = Math.abs(Number(increment));
@@ -106,12 +117,13 @@ export function controls_for(block, generator) {
code = '';
// Determine loop direction at start, in case one of the bounds
// changes during loop execution.
incValue =
generator.nameDB_.getDistinctName(
variable0 + '_inc', NameType.VARIABLE);
incValue = generator.nameDB_!.getDistinctName(
variable0 + '_inc',
NameType.VARIABLE,
);
code += incValue + ' = ';
if (stringUtils.isNumber(increment)) {
code += Math.abs(increment) + '\n';
code += Math.abs(increment as unknown as number) + '\n';
} else {
code += 'math.abs(' + increment + ')\n';
}
@@ -120,25 +132,36 @@ export function controls_for(block, generator) {
code += 'end\n';
}
code +=
'for ' + variable0 + ' = ' + startVar + ', ' + endVar + ', ' + incValue;
'for ' + variable0 + ' = ' + startVar + ', ' + endVar + ', ' + incValue;
code += ' do\n' + branch + 'end\n';
return code;
};
}
export function controls_forEach(block, generator) {
export function controls_forEach(
block: Block,
generator: LuaGenerator,
): string {
// For each loop.
const variable0 =
generator.getVariableName(block.getFieldValue('VAR'));
const variable0 = generator.getVariableName(block.getFieldValue('VAR'));
const argument0 = generator.valueToCode(block, 'LIST', Order.NONE) || '{}';
let branch = generator.statementToCode(block, 'DO');
branch = generator.addLoopTrap(branch, block);
branch = addContinueLabel(branch, generator.INDENT);
const code = 'for _, ' + variable0 + ' in ipairs(' + argument0 + ') do \n' +
branch + 'end\n';
const code =
'for _, ' +
variable0 +
' in ipairs(' +
argument0 +
') do \n' +
branch +
'end\n';
return code;
};
}
export function controls_flow_statements(block, generator) {
export function controls_flow_statements(
block: Block,
generator: LuaGenerator,
): string {
// Flow statements: continue, break.
let xfix = '';
if (generator.STATEMENT_PREFIX) {
@@ -151,7 +174,7 @@ export function controls_flow_statements(block, generator) {
xfix += generator.injectId(generator.STATEMENT_SUFFIX, block);
}
if (generator.STATEMENT_PREFIX) {
const loop = block.getSurroundLoop();
const loop = (block as ControlFlowInLoopBlock).getSurroundLoop();
if (loop && !loop.suppressPrefixSuffix) {
// Inject loop's statement prefix here since the regular one at the end
// of the loop will not get executed if 'continue' is triggered.
@@ -166,4 +189,4 @@ export function controls_flow_statements(block, generator) {
return xfix + CONTINUE_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.
* @suppress {checkTypes|globalThis}
*/
// Former goog.module ID: Blockly.Lua
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 {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';
/**
* Order of operation ENUMs.
* http://www.lua.org/manual/5.3/manual.html#3.4.8
* @enum {number}
*/
export const Order = {
ATOMIC: 0, // literals
// prettier-ignore
export enum Order {
ATOMIC = 0, // literals
// The next level was not explicit in documentation and inferred by Ellen.
HIGH: 1, // Function calls, tables[]
EXPONENTIATION: 2, // ^
UNARY: 3, // not # - ~
MULTIPLICATIVE: 4, // * / %
ADDITIVE: 5, // + -
CONCATENATION: 6, // ..
RELATIONAL: 7, // < > <= >= ~= ==
AND: 8, // and
OR: 9, // or
NONE: 99,
};
HIGH = 1, // Function calls, tables[]
EXPONENTIATION = 2, // ^
UNARY = 3, // not # - ~
MULTIPLICATIVE = 4, // * / %
ADDITIVE = 5, // + -
CONCATENATION = 6, // ..
RELATIONAL = 7, // < > <= >= ~= ==
AND = 8, // and
OR = 9, // or
NONE = 99,
}
/**
* Lua code generator class.
@@ -48,8 +48,8 @@ export const Order = {
* option used for lists and text.
*/
export class LuaGenerator extends CodeGenerator {
constructor(name) {
super(name ?? 'Lua');
constructor(name = 'Lua') {
super(name);
this.isInitialized = false;
// 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
// deprecate.warn().)
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
@@ -70,38 +79,39 @@ export class LuaGenerator extends CodeGenerator {
this.addReservedWords(
// Special character
'_,' +
// From theoriginalbit's script:
// https://github.com/espertus/blockly-lua/issues/6
'__inext,assert,bit,colors,colours,coroutine,disk,dofile,error,fs,' +
'fetfenv,getmetatable,gps,help,io,ipairs,keys,loadfile,loadstring,math,' +
'native,next,os,paintutils,pairs,parallel,pcall,peripheral,print,' +
'printError,rawequal,rawget,rawset,read,rednet,redstone,rs,select,' +
'setfenv,setmetatable,sleep,string,table,term,textutils,tonumber,' +
'tostring,turtle,type,unpack,vector,write,xpcall,_VERSION,__indext,' +
// Not included in the script, probably because it wasn't enabled:
'HTTP,' +
// Keywords (http://www.lua.org/pil/1.3.html).
'and,break,do,else,elseif,end,false,for,function,if,in,local,nil,not,' +
'or,repeat,return,then,true,until,while,' +
// Metamethods (http://www.lua.org/manual/5.2/manual.html).
'add,sub,mul,div,mod,pow,unm,concat,len,eq,lt,le,index,newindex,call,' +
// Basic functions (http://www.lua.org/manual/5.2/manual.html,
// section 6.1).
'assert,collectgarbage,dofile,error,_G,getmetatable,inpairs,load,' +
'loadfile,next,pairs,pcall,print,rawequal,rawget,rawlen,rawset,select,' +
'setmetatable,tonumber,tostring,type,_VERSION,xpcall,' +
// Modules (http://www.lua.org/manual/5.2/manual.html, section 6.3).
'require,package,string,table,math,bit32,io,file,os,debug'
// From theoriginalbit's script:
// https://github.com/espertus/blockly-lua/issues/6
'__inext,assert,bit,colors,colours,coroutine,disk,dofile,error,fs,' +
'fetfenv,getmetatable,gps,help,io,ipairs,keys,loadfile,loadstring,math,' +
'native,next,os,paintutils,pairs,parallel,pcall,peripheral,print,' +
'printError,rawequal,rawget,rawset,read,rednet,redstone,rs,select,' +
'setfenv,setmetatable,sleep,string,table,term,textutils,tonumber,' +
'tostring,turtle,type,unpack,vector,write,xpcall,_VERSION,__indext,' +
// Not included in the script, probably because it wasn't enabled:
'HTTP,' +
// Keywords (http://www.lua.org/pil/1.3.html).
'and,break,do,else,elseif,end,false,for,function,if,in,local,nil,not,' +
'or,repeat,return,then,true,until,while,' +
// Metamethods (http://www.lua.org/manual/5.2/manual.html).
'add,sub,mul,div,mod,pow,unm,concat,len,eq,lt,le,index,newindex,call,' +
// Basic functions (http://www.lua.org/manual/5.2/manual.html,
// section 6.1).
'assert,collectgarbage,dofile,error,_G,getmetatable,inpairs,load,' +
'loadfile,next,pairs,pcall,print,rawequal,rawget,rawlen,rawset,select,' +
'setmetatable,tonumber,tostring,type,_VERSION,xpcall,' +
// Modules (http://www.lua.org/manual/5.2/manual.html, section 6.3).
'require,package,string,table,math,bit32,io,file,os,debug',
);
}
/**
* Initialise the database of variable names.
* @param {!Workspace} workspace Workspace to generate code from.
*
* @param workspace Workspace to generate code from.
*/
init(workspace) {
init(workspace: Workspace) {
// Call Blockly.CodeGenerator's init.
super.init();
super.init(workspace);
if (!this.nameDB_) {
this.nameDB_ = new Names(this.RESERVED_WORDS_);
@@ -113,73 +123,77 @@ export class LuaGenerator extends CodeGenerator {
this.nameDB_.populateProcedures(workspace);
this.isInitialized = true;
};
}
/**
* 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.
const definitions = Object.values(this.definitions_);
// Call Blockly.CodeGenerator's finish.
code = super.finish(code);
this.isInitialized = false;
this.nameDB_.reset();
this.nameDB_!.reset();
return definitions.join('\n\n') + '\n\n\n' + code;
};
}
/**
* Naked values are top-level blocks with outputs that aren't plugged into
* anything. In Lua, an expression is not a legal statement, so we must assign
* the value to the (conventionally ignored) _.
* http://lua-users.org/wiki/ExpressionsAsStatements
* @param {string} line Line of generated code.
* @return {string} Legal line of code.
*
* @param line Line of generated code.
* @return Legal line of code.
*/
scrubNakedValue(line) {
scrubNakedValue(line: string): string {
return 'local _ = ' + line + '\n';
};
}
/**
* Encode a string as a properly escaped Lua string, complete with
* quotes.
* @param {string} string Text to encode.
* @return {string} Lua string.
*
* @param string Text to encode.
* @returns Lua string.
*/
quote_(string) {
string = string.replace(/\\/g, '\\\\')
.replace(/\n/g, '\\\n')
.replace(/'/g, '\\\'');
return '\'' + string + '\'';
};
quote_(string: string): string {
string = string
.replace(/\\/g, '\\\\')
.replace(/\n/g, '\\\n')
.replace(/'/g, "\\'");
return "'" + string + "'";
}
/**
* Encode a string as a properly escaped multiline Lua string, complete with
* quotes.
* @param {string} string Text to encode.
* @return {string} Lua string.
*
* @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_);
// Join with the following, plus a newline:
// .. '\n' ..
return lines.join(' .. \'\\n\' ..\n');
};
return lines.join(" .. '\\n' ..\n");
}
/**
* Common tasks for generating Lua from blocks.
* Handles comments for the specified block and any connected value blocks.
* Calls any statements following this block.
* @param {!Block} block The current block.
* @param {string} code The Lua code created for this block.
* @param {boolean=} opt_thisOnly True to generate code for only this statement.
* @return {string} Lua code with comments and subsequent blocks added.
* @protected
* @param block The current block.
* @param code The Lua code created for this block.
* @param thisOnly True to generate code for only this statement.
* @returns Lua code with comments and subsequent blocks added.
*/
scrub_(block, code, opt_thisOnly) {
scrub_(block: Block, code: string, thisOnly = false): string {
let commentCode = '';
// Only collect comments for blocks that aren't inline.
if (!block.outputConnection || !block.outputConnection.targetConnection) {
@@ -193,7 +207,7 @@ export class LuaGenerator extends CodeGenerator {
// Don't collect comments for nested statements.
for (let i = 0; i < block.inputList.length; i++) {
if (block.inputList[i].type === inputTypes.VALUE) {
const childBlock = block.inputList[i].connection.targetBlock();
const childBlock = block.inputList[i].connection!.targetBlock();
if (childBlock) {
comment = this.allNestedComments(childBlock);
if (comment) {
@@ -203,8 +217,9 @@ export class LuaGenerator extends CodeGenerator {
}
}
}
const nextBlock = block.nextConnection && block.nextConnection.targetBlock();
const nextCode = opt_thisOnly ? '' : this.blockToCode(nextBlock);
const nextBlock =
block.nextConnection && block.nextConnection.targetBlock();
const nextCode = thisOnly ? '' : this.blockToCode(nextBlock);
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
import type {Block} from '../../core/block.js';
import type {LuaGenerator} from './lua_generator.js';
import {Order} from './lua_generator.js';
export function math_number(block, generator) {
export function math_number(
block: Block,
generator: LuaGenerator,
): [string, Order] {
// Numeric value.
const code = Number(block.getFieldValue('NUM'));
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.
const OPERATORS = {
const OPERATORS: Record<string, [string, Order]> = {
'ADD': [' + ', Order.ADDITIVE],
'MINUS': [' - ', Order.ADDITIVE],
'MULTIPLY': [' * ', Order.MULTIPLICATIVE],
'DIVIDE': [' / ', Order.MULTIPLICATIVE],
'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 order = tuple[1];
const argument0 = generator.valueToCode(block, 'A', order) || '0';
const argument1 = generator.valueToCode(block, 'B', order) || '0';
const code = argument0 + operator + argument1;
return [code, order];
};
}
export function math_single(block, generator) {
export function math_single(
block: Block,
generator: LuaGenerator,
): [string, Order] {
// Math operators with single operand.
const operator = block.getFieldValue('OP');
let arg;
@@ -106,11 +117,14 @@ export function math_single(block, generator) {
throw Error('Unknown math operator: ' + operator);
}
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.
const CONSTANTS = {
const CONSTANTS: Record<string, [string, Order]> = {
'PI': ['math.pi', Order.HIGH],
'E': ['math.exp(1)', Order.HIGH],
'GOLDEN_RATIO': ['(1 + math.sqrt(5)) / 2', Order.MULTIPLICATIVE],
@@ -119,12 +133,15 @@ export function math_constant(block, generator) {
'INFINITY': ['math.huge', Order.HIGH],
};
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
// 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],
'ODD': [' % 2 == 1', 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 [suffix, inputOrder, outputOrder] = PROPERTIES[dropdownProperty];
const numberToCheck = generator.valueToCode(block, 'NUMBER_TO_CHECK',
inputOrder) || '0';
const numberToCheck =
generator.valueToCode(block, 'NUMBER_TO_CHECK', inputOrder) || '0';
let code;
if (dropdownProperty === 'PRIME') {
// Prime is a special case as it is not a one-liner test.
const functionName = generator.provideFunction_('math_isPrime', `
const functionName = generator.provideFunction_(
'math_isPrime',
`
function ${generator.FUNCTION_NAME_PLACEHOLDER_}(n)
-- https://en.wikipedia.org/wiki/Primality_test#Naive_methods
if n == 2 or n == 3 then
@@ -159,11 +178,12 @@ function ${generator.FUNCTION_NAME_PLACEHOLDER_}(n)
end
return true
end
`);
`,
);
code = functionName + '(' + numberToCheck + ')';
} else if (dropdownProperty === 'DIVISIBLE_BY') {
const divisor = generator.valueToCode(block, 'DIVISOR',
Order.MULTIPLICATIVE) || '0';
const divisor =
generator.valueToCode(block, 'DIVISOR', Order.MULTIPLICATIVE) || '0';
// 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.
if (divisor === '0') {
@@ -177,23 +197,25 @@ end
code = numberToCheck + suffix;
}
return [code, outputOrder];
};
}
export function math_change(block, generator) {
export function math_change(block: Block, generator: LuaGenerator): string {
// Add to a variable in place.
const argument0 =
generator.valueToCode(block, 'DELTA', Order.ADDITIVE) || '0';
const varName =
generator.getVariableName(block.getFieldValue('VAR'));
generator.valueToCode(block, 'DELTA', Order.ADDITIVE) || '0';
const varName = generator.getVariableName(block.getFieldValue('VAR'));
return varName + ' = ' + varName + ' + ' + argument0 + '\n';
};
}
// Rounding functions have a single operand.
export const math_round = math_single;
// Trigonometry functions have a single operand.
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.
const func = block.getFieldValue('OP');
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.
function provideSum() {
return generator.provideFunction_('math_sum', `
return generator.provideFunction_(
'math_sum',
`
function ${generator.FUNCTION_NAME_PLACEHOLDER_}(t)
local result = 0
for _, v in ipairs(t) do
@@ -209,7 +233,8 @@ function ${generator.FUNCTION_NAME_PLACEHOLDER_}(t)
end
return result
end
`);
`,
);
}
switch (func) {
@@ -219,7 +244,9 @@ end
case 'MIN':
// Returns 0 for the empty list.
functionName = generator.provideFunction_('math_min', `
functionName = generator.provideFunction_(
'math_min',
`
function ${generator.FUNCTION_NAME_PLACEHOLDER_}(t)
if #t == 0 then
return 0
@@ -232,24 +259,30 @@ function ${generator.FUNCTION_NAME_PLACEHOLDER_}(t)
end
return result
end
`);
`,
);
break;
case 'AVERAGE':
// Returns 0 for the empty list.
functionName = generator.provideFunction_('math_average', `
functionName = generator.provideFunction_(
'math_average',
`
function ${generator.FUNCTION_NAME_PLACEHOLDER_}(t)
if #t == 0 then
return 0
end
return ${provideSum()}(t) / #t
end
`);
`,
);
break;
case 'MAX':
// Returns 0 for the empty list.
functionName = generator.provideFunction_('math_max', `
functionName = generator.provideFunction_(
'math_max',
`
function ${generator.FUNCTION_NAME_PLACEHOLDER_}(t)
if #t == 0 then
return 0
@@ -262,12 +295,15 @@ function ${generator.FUNCTION_NAME_PLACEHOLDER_}(t)
end
return result
end
`);
`,
);
break;
case 'MEDIAN':
// This operation excludes non-numbers.
functionName = generator.provideFunction_('math_median', `
functionName = generator.provideFunction_(
'math_median',
`
function ${generator.FUNCTION_NAME_PLACEHOLDER_}(t)
-- Source: http://lua-users.org/wiki/SimpleStats
if #t == 0 then
@@ -286,14 +322,17 @@ function ${generator.FUNCTION_NAME_PLACEHOLDER_}(t)
return temp[math.ceil(#temp / 2)]
end
end
`);
`,
);
break;
case 'MODE':
// As a list of numbers can contain more than one mode,
// the returned result is provided as an array.
// The generator version includes non-numbers.
functionName = generator.provideFunction_('math_modes', `
functionName = generator.provideFunction_(
'math_modes',
`
function ${generator.FUNCTION_NAME_PLACEHOLDER_}(t)
-- Source: http://lua-users.org/wiki/SimpleStats
local counts = {}
@@ -318,11 +357,14 @@ function ${generator.FUNCTION_NAME_PLACEHOLDER_}(t)
end
return temp
end
`);
`,
);
break;
case 'STD_DEV':
functionName = generator.provideFunction_('math_standard_deviation', `
functionName = generator.provideFunction_(
'math_standard_deviation',
`
function ${generator.FUNCTION_NAME_PLACEHOLDER_}(t)
local m
local vm
@@ -340,66 +382,92 @@ function ${generator.FUNCTION_NAME_PLACEHOLDER_}(t)
result = math.sqrt(total / (count-1))
return result
end
`);
`,
);
break;
case 'RANDOM':
functionName = generator.provideFunction_('math_random_list', `
functionName = generator.provideFunction_(
'math_random_list',
`
function ${generator.FUNCTION_NAME_PLACEHOLDER_}(t)
if #t == 0 then
return nil
end
return t[math.random(#t)]
end
`);
`,
);
break;
default:
throw Error('Unknown operator: ' + func);
}
return [functionName + '(' + list + ')', Order.HIGH];
};
}
export function math_modulo(block, generator) {
export function math_modulo(
block: Block,
generator: LuaGenerator,
): [string, Order] {
// Remainder computation.
const argument0 =
generator.valueToCode(block, 'DIVIDEND', Order.MULTIPLICATIVE) || '0';
generator.valueToCode(block, 'DIVIDEND', Order.MULTIPLICATIVE) || '0';
const argument1 =
generator.valueToCode(block, 'DIVISOR', Order.MULTIPLICATIVE) || '0';
generator.valueToCode(block, 'DIVISOR', Order.MULTIPLICATIVE) || '0';
const code = argument0 + ' % ' + argument1;
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.
const argument0 = generator.valueToCode(block, 'VALUE', Order.NONE) || '0';
const argument1 =
generator.valueToCode(block, 'LOW', Order.NONE) || '-math.huge';
generator.valueToCode(block, 'LOW', Order.NONE) || '-math.huge';
const argument2 =
generator.valueToCode(block, 'HIGH', Order.NONE) || 'math.huge';
const code = 'math.min(math.max(' + argument0 + ', ' + argument1 + '), ' +
argument2 + ')';
generator.valueToCode(block, 'HIGH', Order.NONE) || 'math.huge';
const code =
'math.min(math.max(' +
argument0 +
', ' +
argument1 +
'), ' +
argument2 +
')';
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].
const argument0 = generator.valueToCode(block, 'FROM', Order.NONE) || '0';
const argument1 = generator.valueToCode(block, 'TO', Order.NONE) || '0';
const code = 'math.random(' + argument0 + ', ' + argument1 + ')';
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.
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.
const argument0 = generator.valueToCode(block, 'X', Order.NONE) || '0';
const argument1 = generator.valueToCode(block, 'Y', Order.NONE) || '0';
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
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';
export function procedures_defreturn(block, generator) {
export function procedures_defreturn(
block: Block,
generator: LuaGenerator,
): null {
// Define a procedure with a return value.
const funcName =
generator.getProcedureName(block.getFieldValue('NAME'));
const funcName = generator.getProcedureName(block.getFieldValue('NAME'));
let xfix1 = '';
if (generator.STATEMENT_PREFIX) {
xfix1 += generator.injectId(generator.STATEMENT_PREFIX, block);
@@ -30,8 +34,9 @@ export function procedures_defreturn(block, generator) {
let loopTrap = '';
if (generator.INFINITE_LOOP_TRAP) {
loopTrap = generator.prefixLines(
generator.injectId(
generator.INFINITE_LOOP_TRAP, block), generator.INDENT);
generator.injectId(generator.INFINITE_LOOP_TRAP, block),
generator.INDENT,
);
}
let branch = generator.statementToCode(block, 'STACK');
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++) {
args[i] = generator.getVariableName(variables[i]);
}
let code = 'function ' + funcName + '(' + args.join(', ') + ')\n' + xfix1 +
loopTrap + branch + xfix2 + returnValue + 'end\n';
let code =
'function ' +
funcName +
'(' +
args.join(', ') +
')\n' +
xfix1 +
loopTrap +
branch +
xfix2 +
returnValue +
'end\n';
code = generator.scrub_(block, code);
// 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;
};
}
// Defining a procedure without a return value uses the same generator as
// a procedure with a return value.
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.
const funcName =
generator.getProcedureName(block.getFieldValue('NAME'));
const funcName = generator.getProcedureName(block.getFieldValue('NAME'));
const args = [];
const variables = block.getVars();
for (let i = 0; i < variables.length; i++) {
@@ -73,30 +92,39 @@ export function procedures_callreturn(block, generator) {
}
const code = funcName + '(' + args.join(', ') + ')';
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.
// Generated code is for a function call as a statement is the same as a
// function call as a value, with the addition of line ending.
const tuple = generator.forBlock['procedures_callreturn'](block, generator);
const tuple = generator.forBlock['procedures_callreturn'](
block,
generator,
) as [string, number];
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.
const condition =
generator.valueToCode(block, 'CONDITION', Order.NONE) || 'false';
generator.valueToCode(block, 'CONDITION', Order.NONE) || 'false';
let code = 'if ' + condition + ' then\n';
if (generator.STATEMENT_SUFFIX) {
// Inject any statement suffix here since the regular one at the end
// will not get executed if the return is triggered.
code +=
generator.prefixLines(
generator.injectId(generator.STATEMENT_SUFFIX, block),
generator.INDENT);
code += generator.prefixLines(
generator.injectId(generator.STATEMENT_SUFFIX, block),
generator.INDENT,
);
}
if (block.hasReturnValue_) {
if ((block as IfReturnBlock).hasReturnValue_) {
const value = generator.valueToCode(block, 'VALUE', Order.NONE) || 'nil';
code += generator.INDENT + 'return ' + value + '\n';
} else {
@@ -104,4 +132,4 @@ export function procedures_ifreturn(block, generator) {
}
code += 'end\n';
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
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';
export function text(block, generator) {
export function text(block: Block, generator: LuaGenerator): [string, Order] {
// Text value.
const code = generator.quote_(block.getFieldValue('TEXT'));
return [code, Order.ATOMIC];
};
}
export function text_multiline(block, generator) {
export function text_multiline(
block: Block,
generator: LuaGenerator,
): [string, Order] {
// Text value.
const code = generator.multiline_quote_(block.getFieldValue('TEXT'));
const order =
code.indexOf('..') !== -1 ? Order.CONCATENATION : Order.ATOMIC;
const order = code.indexOf('..') !== -1 ? Order.CONCATENATION : Order.ATOMIC;
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.
if (block.itemCount_ === 0) {
if (joinBlock.itemCount_ === 0) {
return ["''", Order.ATOMIC];
} else if (block.itemCount_ === 1) {
} else if (joinBlock.itemCount_ === 1) {
const element = generator.valueToCode(block, 'ADD0', Order.NONE) || "''";
const code = 'tostring(' + element + ')';
return [code, Order.HIGH];
} else if (block.itemCount_ === 2) {
} else if (joinBlock.itemCount_ === 2) {
const element0 =
generator.valueToCode(block, 'ADD0', Order.CONCATENATION) || "''";
generator.valueToCode(block, 'ADD0', Order.CONCATENATION) || "''";
const element1 =
generator.valueToCode(block, 'ADD1', Order.CONCATENATION) || "''";
generator.valueToCode(block, 'ADD1', Order.CONCATENATION) || "''";
const code = element0 + ' .. ' + element1;
return [code, Order.CONCATENATION];
} else {
const elements = [];
for (let i = 0; i < block.itemCount_; i++) {
elements[i] =
generator.valueToCode(block, 'ADD' + i, Order.NONE) || "''";
for (let i = 0; i < joinBlock.itemCount_; i++) {
elements[i] = generator.valueToCode(block, 'ADD' + i, Order.NONE) || "''";
}
const code = 'table.concat({' + elements.join(', ') + '})';
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.
const varName =
generator.getVariableName(block.getFieldValue('VAR'));
const varName = generator.getVariableName(block.getFieldValue('VAR'));
const value =
generator.valueToCode(block, 'TEXT', Order.CONCATENATION) || "''";
generator.valueToCode(block, 'TEXT', Order.CONCATENATION) || "''";
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.
const text = generator.valueToCode(block, 'VALUE', 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?
const text = generator.valueToCode(block, 'VALUE', Order.UNARY) || "''";
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.
const substring = generator.valueToCode(block, 'FIND', Order.NONE) || "''";
const text = generator.valueToCode(block, 'VALUE', Order.NONE) || "''";
let functionName;
if (block.getFieldValue('END') === 'FIRST') {
functionName = generator.provideFunction_('firstIndexOf', `
functionName = generator.provideFunction_(
'firstIndexOf',
`
function ${generator.FUNCTION_NAME_PLACEHOLDER_}(str, substr)
local i = string.find(str, substr, 1, true)
if i == nil then
@@ -88,9 +105,12 @@ function ${generator.FUNCTION_NAME_PLACEHOLDER_}(str, substr)
end
return i
end
`);
`,
);
} else {
functionName = generator.provideFunction_('lastIndexOf', `
functionName = generator.provideFunction_(
'lastIndexOf',
`
function ${generator.FUNCTION_NAME_PLACEHOLDER_}(str, substr)
local i = string.find(string.reverse(str), string.reverse(substr), 1, true)
if i then
@@ -98,27 +118,34 @@ function ${generator.FUNCTION_NAME_PLACEHOLDER_}(str, substr)
end
return 0
end
`);
`,
);
}
const code = functionName + '(' + text + ', ' + substring + ')';
return [code, Order.HIGH];
};
}
export function text_charAt(block, generator) {
export function text_charAt(
block: Block,
generator: LuaGenerator,
): [string, Order] {
// Get letter at index.
// Note: Until January 2013 this block did not have the WHERE input.
const where = block.getFieldValue('WHERE') || 'FROM_START';
const atOrder = (where === 'FROM_END') ? Order.UNARY : Order.NONE;
const atOrder = where === 'FROM_END' ? Order.UNARY : Order.NONE;
const at = generator.valueToCode(block, 'AT', atOrder) || '1';
const text = generator.valueToCode(block, 'VALUE', Order.NONE) || "''";
let code;
if (where === 'RANDOM') {
const functionName = generator.provideFunction_('text_random_letter', `
const functionName = generator.provideFunction_(
'text_random_letter',
`
function ${generator.FUNCTION_NAME_PLACEHOLDER_}(str)
local index = math.random(string.len(str))
return string.sub(str, index, index)
end
`);
`,
);
code = functionName + '(' + text + ')';
} else {
let start;
@@ -139,24 +166,30 @@ end
code = 'string.sub(' + text + ', ' + start + ', ' + start + ')';
} else {
// 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)
return string.sub(str, index, index)
end
`);
`,
);
code = functionName + '(' + text + ', ' + start + ')';
}
}
return [code, Order.HIGH];
};
}
export function text_getSubstring(block, generator) {
export function text_getSubstring(
block: Block,
generator: LuaGenerator,
): [string, Order] {
// Get substring.
const text = generator.valueToCode(block, 'STRING', Order.NONE) || "''";
// Get start index.
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';
let start;
if (where1 === 'FIRST') {
@@ -171,7 +204,7 @@ export function text_getSubstring(block, generator) {
// Get end index.
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';
let end;
if (where2 === 'LAST') {
@@ -185,9 +218,12 @@ export function text_getSubstring(block, generator) {
}
const code = 'string.sub(' + text + ', ' + start + ', ' + end + ')';
return [code, Order.HIGH];
};
}
export function text_changeCase(block, generator) {
export function text_changeCase(
block: Block,
generator: LuaGenerator,
): [string, Order] {
// Change capitalization.
const operator = block.getFieldValue('CASE');
const text = generator.valueToCode(block, 'TEXT', Order.NONE) || "''";
@@ -200,7 +236,9 @@ export function text_changeCase(block, generator) {
// There are shorter versions at
// http://lua-users.org/wiki/SciteTitleCase
// that do not preserve whitespace.
functionName = generator.provideFunction_('text_titlecase', `
functionName = generator.provideFunction_(
'text_titlecase',
`
function ${generator.FUNCTION_NAME_PLACEHOLDER_}(str)
local buf = {}
local inWord = false
@@ -218,28 +256,36 @@ function ${generator.FUNCTION_NAME_PLACEHOLDER_}(str)
end
return table.concat(buf)
end
`);
`,
);
}
const code = functionName + '(' + text + ')';
return [code, Order.HIGH];
};
}
export function text_trim(block, generator) {
export function text_trim(
block: Block,
generator: LuaGenerator,
): [string, Order] {
// Trim spaces.
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 code = 'string.gsub(' + text + ', "' + operator + '", "%1")';
return [code, Order.HIGH];
};
}
export function text_print(block, generator) {
export function text_print(block: Block, generator: LuaGenerator): string {
// Print statement.
const msg = generator.valueToCode(block, 'TEXT', Order.NONE) || "''";
return 'print(' + msg + ')\n';
};
}
export function text_prompt_ext(block, generator) {
export function text_prompt_ext(
block: Block,
generator: LuaGenerator,
): [string, Order] {
// Prompt function.
let msg;
if (block.getField('TEXT')) {
@@ -250,13 +296,16 @@ export function text_prompt_ext(block, generator) {
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)
io.write(msg)
io.flush()
return io.read()
end
`);
`,
);
let code = functionName + '(' + msg + ')';
const toNumber = block.getFieldValue('TYPE') === 'NUMBER';
@@ -264,14 +313,19 @@ end
code = 'tonumber(' + code + ', 10)';
}
return [code, Order.HIGH];
};
}
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 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)
if #needle == 0 then
return #haystack + 1
@@ -288,16 +342,22 @@ function ${generator.FUNCTION_NAME_PLACEHOLDER_}(haystack, needle)
end
return count
end
`);
`,
);
const code = functionName + '(' + text + ', ' + sub + ')';
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 from = generator.valueToCode(block, 'FROM', 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)
local buf = {}
local i = 1
@@ -314,13 +374,17 @@ function ${generator.FUNCTION_NAME_PLACEHOLDER_}(haystack, needle, replacement)
end
return table.concat(buf)
end
`);
`,
);
const code = functionName + '(' + text + ', ' + from + ', ' + to + ')';
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 code = 'string.reverse(' + text + ')';
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
// Lua is dynamically typed.
export {
variables_get as variables_get_dynamic,