mirror of
https://github.com/google/blockly.git
synced 2025-12-16 14:20:10 +01:00
Add a Lua code generator
This is based on the JS generator, with a lot of inspiration from Ellen Spertus's blockly-lua: https://github.com/espertus/blockly-lua All unit tests pass with Lua 5.3.2.
This commit is contained in:
@@ -30,6 +30,7 @@ blockly/
|
||||
|- blocks_compressed.js
|
||||
|- dart_compressed.js
|
||||
|- javascript_compressed.js
|
||||
|- lua_compressed.js
|
||||
|- php_compressed.js
|
||||
`- python_compressed.js
|
||||
|
||||
|
||||
2
build.py
2
build.py
@@ -33,6 +33,7 @@
|
||||
# javascript_compressed.js: The compressed Javascript generator.
|
||||
# python_compressed.js: The compressed Python generator.
|
||||
# dart_compressed.js: The compressed Dart generator.
|
||||
# lua_compressed.js: The compressed Lua generator.
|
||||
# msg/js/<LANG>.js for every language <LANG> defined in msg/js/<LANG>.json.
|
||||
|
||||
import sys
|
||||
@@ -178,6 +179,7 @@ class Gen_compressed(threading.Thread):
|
||||
self.gen_generator("python")
|
||||
self.gen_generator("php")
|
||||
self.gen_generator("dart")
|
||||
self.gen_generator("lua")
|
||||
|
||||
def gen_core(self):
|
||||
target_filename = "blockly_compressed.js"
|
||||
|
||||
@@ -161,6 +161,7 @@
|
||||
<option value="Python">Python</option>
|
||||
<option value="PHP">PHP</option>
|
||||
<option value="Dart">Dart</option>
|
||||
<option value="Lua">Lua</option>
|
||||
</select>
|
||||
</h3>
|
||||
</td>
|
||||
|
||||
@@ -244,7 +244,7 @@ Code.LANG = Code.getLang();
|
||||
* List of tab names.
|
||||
* @private
|
||||
*/
|
||||
Code.TABS_ = ['blocks', 'javascript', 'php', 'python', 'dart', 'xml'];
|
||||
Code.TABS_ = ['blocks', 'javascript', 'php', 'python', 'dart', 'lua', 'xml'];
|
||||
|
||||
Code.selected = 'blocks';
|
||||
|
||||
@@ -341,6 +341,14 @@ Code.renderContent = function() {
|
||||
code = prettyPrintOne(code, 'dart');
|
||||
content.innerHTML = code;
|
||||
}
|
||||
} else if (content.id == 'content_lua') {
|
||||
code = Blockly.Lua.workspaceToCode(Code.workspace);
|
||||
content.textContent = code;
|
||||
if (typeof prettyPrintOne == 'function') {
|
||||
code = content.innerHTML;
|
||||
code = prettyPrintOne(code, 'lua');
|
||||
content.innerHTML = code;
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
@@ -12,6 +12,7 @@
|
||||
<script src="../../python_compressed.js"></script>
|
||||
<script src="../../php_compressed.js"></script>
|
||||
<script src="../../dart_compressed.js"></script>
|
||||
<script src="../../lua_compressed.js"></script>
|
||||
<script src="code.js"></script>
|
||||
</head>
|
||||
<body>
|
||||
@@ -41,6 +42,8 @@
|
||||
<td class="tabmin"> </td>
|
||||
<td id="tab_dart" class="taboff">Dart</td>
|
||||
<td class="tabmin"> </td>
|
||||
<td id="tab_lua" class="taboff">Lua</td>
|
||||
<td class="tabmin"> </td>
|
||||
<td id="tab_xml" class="taboff">XML</td>
|
||||
<td class="tabmax">
|
||||
<button id="trashButton" class="notext" title="...">
|
||||
@@ -67,6 +70,7 @@
|
||||
<pre id="content_php" class="content"></pre>
|
||||
<pre id="content_python" class="content"></pre>
|
||||
<pre id="content_dart" class="content"></pre>
|
||||
<pre id="content_lua" class="content"></pre>
|
||||
<textarea id="content_xml" class="content" wrap="off"></textarea>
|
||||
|
||||
<xml id="toolbox" style="display: none">
|
||||
|
||||
@@ -168,7 +168,7 @@
|
||||
</td>
|
||||
<td>
|
||||
<div><a href="code/index.html">Code Editor</a></div>
|
||||
<div>Export a Blockly program into JavaScript, Python, PHP, Dart or XML.</div>
|
||||
<div>Export a Blockly program into JavaScript, Python, PHP, Dart, Lua or XML.</div>
|
||||
</td>
|
||||
</tr>
|
||||
|
||||
|
||||
188
generators/lua.js
Normal file
188
generators/lua.js
Normal file
@@ -0,0 +1,188 @@
|
||||
/**
|
||||
* @license
|
||||
* Visual Blocks Language
|
||||
*
|
||||
* Copyright 2016 Google Inc.
|
||||
* https://developers.google.com/blockly/
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
/**
|
||||
* @fileoverview Helper functions for generating Lua for blocks.
|
||||
* @author rodrigoq@google.com (Rodrigo Queiro)
|
||||
* Based on Ellen Spertus's blocky-lua project.
|
||||
*/
|
||||
'use strict';
|
||||
|
||||
goog.provide('Blockly.Lua');
|
||||
|
||||
goog.require('Blockly.Generator');
|
||||
|
||||
|
||||
/**
|
||||
* Lua code generator.
|
||||
* @type {!Blockly.Generator}
|
||||
*/
|
||||
Blockly.Lua = new Blockly.Generator('Lua');
|
||||
|
||||
/**
|
||||
* List of illegal variable names.
|
||||
* This is not intended to be a security feature. Blockly is 100% client-side,
|
||||
* so bypassing this list is trivial. This is intended to prevent users from
|
||||
* accidentally clobbering a built-in object or function.
|
||||
* @private
|
||||
*/
|
||||
Blockly.Lua.addReservedWords(
|
||||
// Special character
|
||||
'_' +
|
||||
// From theoriginalbit's script:
|
||||
// https://github.com/espertus/blockly-lua/issues/6
|
||||
'__inext,assert,bit,colors,colours,coroutine,disk,dofile,error,fs,' +
|
||||
'fetfenv,getmetatable,gps,help,io,ipairs,keys,loadfile,loadstring,math,' +
|
||||
'native,next,os,paintutils,pairs,parallel,pcall,peripheral,print,' +
|
||||
'printError,rawequal,rawget,rawset,read,rednet,redstone,rs,select,' +
|
||||
'setfenv,setmetatable,sleep,string,table,term,textutils,tonumber,' +
|
||||
'tostring,turtle,type,unpack,vector,write,xpcall,_VERSION,__indext,' +
|
||||
// Not included in the script, probably because it wasn't enabled:
|
||||
'HTTP,' +
|
||||
// Keywords (http://www.lua.org/pil/1.3.html).
|
||||
'and,break,do,else,elseif,end,false,for,function,if,in,local,nil,not,or,' +
|
||||
'repeat,return,then,true,until,while,' +
|
||||
// Metamethods (http://www.lua.org/manual/5.2/manual.html).
|
||||
'add,sub,mul,div,mod,pow,unm,concat,len,eq,lt,le,index,newindex,call,' +
|
||||
// Basic functions (http://www.lua.org/manual/5.2/manual.html, section 6.1).
|
||||
'assert,collectgarbage,dofile,error,_G,getmetatable,inpairs,load,' +
|
||||
'loadfile,next,pairs,pcall,print,rawequal,rawget,rawlen,rawset,select,' +
|
||||
'setmetatable,tonumber,tostring,type,_VERSION,xpcall,' +
|
||||
// Modules (http://www.lua.org/manual/5.2/manual.html, section 6.3).
|
||||
'require,package,string,table,math,bit32,io,file,os,debug'
|
||||
);
|
||||
|
||||
/**
|
||||
* Order of operation ENUMs.
|
||||
* http://www.lua.org/manual/5.3/manual.html#3.4.8
|
||||
*/
|
||||
Blockly.Lua.ORDER_ATOMIC = 0; // literals
|
||||
// The next level was not explicit in documentation and inferred by Ellen.
|
||||
Blockly.Lua.ORDER_HIGH = 1; // Function calls, tables[]
|
||||
Blockly.Lua.ORDER_EXPONENTIATION = 2; // ^
|
||||
Blockly.Lua.ORDER_UNARY = 3; // not # - ()
|
||||
Blockly.Lua.ORDER_MULTIPLICATIVE = 4; // * / %
|
||||
Blockly.Lua.ORDER_ADDITIVE = 5; // + -
|
||||
Blockly.Lua.ORDER_CONCATENATION = 6; // ..
|
||||
Blockly.Lua.ORDER_RELATIONAL = 7; // < > <= >= ~= ==
|
||||
Blockly.Lua.ORDER_AND = 8; // and
|
||||
Blockly.Lua.ORDER_OR = 9; // or
|
||||
Blockly.Lua.ORDER_NONE = 99;
|
||||
|
||||
/**
|
||||
* Initialise the database of variable names.
|
||||
* @param {!Blockly.Workspace} workspace Workspace to generate code from.
|
||||
*/
|
||||
Blockly.Lua.init = function(workspace) {
|
||||
// Create a dictionary of definitions to be printed before the code.
|
||||
Blockly.Lua.definitions_ = Object.create(null);
|
||||
// Create a dictionary mapping desired function names in definitions_
|
||||
// to actual function names (to avoid collisions with user functions).
|
||||
Blockly.Lua.functionNames_ = Object.create(null);
|
||||
|
||||
if (!Blockly.Lua.variableDB_) {
|
||||
Blockly.Lua.variableDB_ =
|
||||
new Blockly.Names(Blockly.Lua.RESERVED_WORDS_);
|
||||
} else {
|
||||
Blockly.Lua.variableDB_.reset();
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* Prepend the generated code with the variable definitions.
|
||||
* @param {string} code Generated code.
|
||||
* @return {string} Completed code.
|
||||
*/
|
||||
Blockly.Lua.finish = function(code) {
|
||||
// Convert the definitions dictionary into a list.
|
||||
var definitions = [];
|
||||
for (var name in Blockly.Lua.definitions_) {
|
||||
definitions.push(Blockly.Lua.definitions_[name]);
|
||||
}
|
||||
// Clean up temporary data.
|
||||
delete Blockly.Lua.definitions_;
|
||||
delete Blockly.Lua.functionNames_;
|
||||
Blockly.Lua.variableDB_.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.
|
||||
*/
|
||||
Blockly.Lua.scrubNakedValue = function(line) {
|
||||
return 'local _ = ' + line + '\n';
|
||||
};
|
||||
|
||||
/**
|
||||
* Encode a string as a properly escaped Lua string, complete with
|
||||
* quotes.
|
||||
* @param {string} string Text to encode.
|
||||
* @return {string} Lua string.
|
||||
* @private
|
||||
*/
|
||||
Blockly.Lua.quote_ = function(string) {
|
||||
// TODO: This is a quick hack. Replace with goog.string.quote
|
||||
string = string.replace(/\\/g, '\\\\')
|
||||
.replace(/\n/g, '\\\n')
|
||||
.replace(/'/g, '\\\'');
|
||||
return '\'' + string + '\'';
|
||||
};
|
||||
|
||||
/**
|
||||
* 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 {!Blockly.Block} block The current block.
|
||||
* @param {string} code The Lua code created for this block.
|
||||
* @return {string} Lua code with comments and subsequent blocks added.
|
||||
* @private
|
||||
*/
|
||||
Blockly.Lua.scrub_ = function(block, code) {
|
||||
var commentCode = '';
|
||||
// Only collect comments for blocks that aren't inline.
|
||||
if (!block.outputConnection || !block.outputConnection.targetConnection) {
|
||||
// Collect comment for this block.
|
||||
var comment = block.getCommentText();
|
||||
if (comment) {
|
||||
commentCode += Blockly.Lua.prefixLines(comment, '-- ') + '\n';
|
||||
}
|
||||
// Collect comments for all value arguments.
|
||||
// Don't collect comments for nested statements.
|
||||
for (var x = 0; x < block.inputList.length; x++) {
|
||||
if (block.inputList[x].type == Blockly.INPUT_VALUE) {
|
||||
var childBlock = block.inputList[x].connection.targetBlock();
|
||||
if (childBlock) {
|
||||
comment = Blockly.Lua.allNestedComments(childBlock);
|
||||
if (comment) {
|
||||
commentCode += Blockly.Lua.prefixLines(comment, '-- ');
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
var nextBlock = block.nextConnection && block.nextConnection.targetBlock();
|
||||
var nextCode = Blockly.Lua.blockToCode(nextBlock);
|
||||
return commentCode + code + nextCode;
|
||||
};
|
||||
90
generators/lua/colour.js
Normal file
90
generators/lua/colour.js
Normal file
@@ -0,0 +1,90 @@
|
||||
/**
|
||||
* @license
|
||||
* Visual Blocks Language
|
||||
*
|
||||
* Copyright 2016 Google Inc.
|
||||
* https://developers.google.com/blockly/
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
/**
|
||||
* @fileoverview Generating Lua for colour blocks.
|
||||
* @author rodrigoq@google.com (Rodrigo Queiro)
|
||||
*/
|
||||
'use strict';
|
||||
|
||||
goog.provide('Blockly.Lua.colour');
|
||||
|
||||
goog.require('Blockly.Lua');
|
||||
|
||||
|
||||
Blockly.Lua['colour_picker'] = function(block) {
|
||||
// Colour picker.
|
||||
var code = '\'' + block.getFieldValue('COLOUR') + '\'';
|
||||
return [code, Blockly.Lua.ORDER_ATOMIC];
|
||||
};
|
||||
|
||||
Blockly.Lua['colour_random'] = function(block) {
|
||||
// Generate a random colour.
|
||||
var code = 'string.format("#%06x", math.random(0, 2^24 - 1))';
|
||||
return [code, Blockly.Lua.ORDER_HIGH];
|
||||
};
|
||||
|
||||
Blockly.Lua['colour_rgb'] = function(block) {
|
||||
// Compose a colour from RGB components expressed as percentages.
|
||||
var functionName = Blockly.Lua.provideFunction_(
|
||||
'colour_rgb',
|
||||
['function ' + Blockly.Lua.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']);
|
||||
var r = Blockly.Lua.valueToCode(block, 'RED',
|
||||
Blockly.Lua.ORDER_NONE) || 0;
|
||||
var g = Blockly.Lua.valueToCode(block, 'GREEN',
|
||||
Blockly.Lua.ORDER_NONE) || 0;
|
||||
var b = Blockly.Lua.valueToCode(block, 'BLUE',
|
||||
Blockly.Lua.ORDER_NONE) || 0;
|
||||
var code = functionName + '(' + r + ', ' + g + ', ' + b + ')';
|
||||
return [code, Blockly.Lua.ORDER_HIGH];
|
||||
};
|
||||
|
||||
Blockly.Lua['colour_blend'] = function(block) {
|
||||
// Blend two colours together.
|
||||
var functionName = Blockly.Lua.provideFunction_(
|
||||
'colour_blend',
|
||||
['function ' + Blockly.Lua.FUNCTION_NAME_PLACEHOLDER_ +
|
||||
'(colour1, colour2, ratio)',
|
||||
' local r1 = tonumber(string.sub(colour1, 2, 3), 16)',
|
||||
' local r2 = tonumber(string.sub(colour2, 2, 3), 16)',
|
||||
' local g1 = tonumber(string.sub(colour1, 4, 5), 16)',
|
||||
' local g2 = tonumber(string.sub(colour2, 4, 5), 16)',
|
||||
' local b1 = tonumber(string.sub(colour1, 6, 7), 16)',
|
||||
' local b2 = tonumber(string.sub(colour2, 6, 7), 16)',
|
||||
' local ratio = math.min(1, math.max(0, ratio))',
|
||||
' local r = math.floor(r1 * (1 - ratio) + r2 * ratio + .5)',
|
||||
' local g = math.floor(g1 * (1 - ratio) + g2 * ratio + .5)',
|
||||
' local b = math.floor(b1 * (1 - ratio) + b2 * ratio + .5)',
|
||||
' return string.format("#%02x%02x%02x", r, g, b)',
|
||||
'end']);
|
||||
var colour1 = Blockly.Lua.valueToCode(block, 'COLOUR1',
|
||||
Blockly.Lua.ORDER_NONE) || '\'#000000\'';
|
||||
var colour2 = Blockly.Lua.valueToCode(block, 'COLOUR2',
|
||||
Blockly.Lua.ORDER_NONE) || '\'#000000\'';
|
||||
var ratio = Blockly.Lua.valueToCode(block, 'RATIO',
|
||||
Blockly.Lua.ORDER_NONE) || 0;
|
||||
var code = functionName + '(' + colour1 + ', ' + colour2 + ', ' + ratio + ')';
|
||||
return [code, Blockly.Lua.ORDER_HIGH];
|
||||
};
|
||||
363
generators/lua/lists.js
Normal file
363
generators/lua/lists.js
Normal file
@@ -0,0 +1,363 @@
|
||||
/**
|
||||
* @license
|
||||
* Visual Blocks Language
|
||||
*
|
||||
* Copyright 2016 Google Inc.
|
||||
* https://developers.google.com/blockly/
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
/**
|
||||
* @fileoverview Generating Lua for list blocks.
|
||||
* @author rodrigoq@google.com (Rodrigo Queiro)
|
||||
*/
|
||||
'use strict';
|
||||
|
||||
goog.provide('Blockly.Lua.lists');
|
||||
|
||||
goog.require('Blockly.Lua');
|
||||
|
||||
|
||||
Blockly.Lua['lists_create_empty'] = function(block) {
|
||||
// Create an empty list.
|
||||
// List literals must be parenthesized before indexing into.
|
||||
return ['({})', Blockly.Lua.ORDER_ATOMIC];
|
||||
};
|
||||
|
||||
Blockly.Lua['lists_create_with'] = function(block) {
|
||||
// Create a list with any number of elements of any type.
|
||||
var code = new Array(block.itemCount_);
|
||||
for (var n = 0; n < block.itemCount_; n++) {
|
||||
code[n] = Blockly.Lua.valueToCode(block, 'ADD' + n,
|
||||
Blockly.Lua.ORDER_NONE) || 'None';
|
||||
}
|
||||
code = '({' + code.join(', ') + '})';
|
||||
return [code, Blockly.Lua.ORDER_ATOMIC];
|
||||
};
|
||||
|
||||
Blockly.Lua['lists_repeat'] = function(block) {
|
||||
// Create a list with one element repeated.
|
||||
var functionName = Blockly.Lua.provideFunction_(
|
||||
'create_list_repeated',
|
||||
['function ' + Blockly.Lua.FUNCTION_NAME_PLACEHOLDER_ + '(item, count)',
|
||||
' local t = {}',
|
||||
' for i = 1, count do',
|
||||
' table.insert(t, item)',
|
||||
' end',
|
||||
' return t',
|
||||
'end']);
|
||||
var argument0 = Blockly.Lua.valueToCode(block, 'ITEM',
|
||||
Blockly.Lua.ORDER_NONE) || 'None';
|
||||
var argument1 = Blockly.Lua.valueToCode(block, 'NUM',
|
||||
Blockly.Lua.ORDER_NONE) || '0';
|
||||
var code = functionName + '(' + argument0 + ', ' + argument1 + ')';
|
||||
return [code, Blockly.Lua.ORDER_HIGH];
|
||||
};
|
||||
|
||||
Blockly.Lua['lists_length'] = function(block) {
|
||||
// String or array length.
|
||||
var argument0 = Blockly.Lua.valueToCode(block, 'VALUE',
|
||||
Blockly.Lua.ORDER_HIGH) || '({})';
|
||||
return ['#' + argument0, Blockly.Lua.ORDER_HIGH];
|
||||
};
|
||||
|
||||
Blockly.Lua['lists_isEmpty'] = function(block) {
|
||||
// Is the string null or array empty?
|
||||
var argument0 = Blockly.Lua.valueToCode(block, 'VALUE',
|
||||
Blockly.Lua.ORDER_HIGH) || '({})';
|
||||
var code = '#' + argument0 + ' == 0';
|
||||
return [code, Blockly.Lua.ORDER_RELATIONAL];
|
||||
};
|
||||
|
||||
Blockly.Lua['lists_indexOf'] = function(block) {
|
||||
// Find an item in the list.
|
||||
var argument0 = Blockly.Lua.valueToCode(block, 'FIND',
|
||||
Blockly.Lua.ORDER_NONE) || '\'\'';
|
||||
var argument1 = Blockly.Lua.valueToCode(block, 'VALUE',
|
||||
Blockly.Lua.ORDER_NONE) || '({})';
|
||||
var functionName;
|
||||
if (block.getTitleValue('END') == 'FIRST') {
|
||||
functionName = Blockly.Lua.provideFunction_(
|
||||
'first_index',
|
||||
['function ' + Blockly.Lua.FUNCTION_NAME_PLACEHOLDER_ + '(t, elem)',
|
||||
' for k, v in ipairs(t) do',
|
||||
' if v == elem then',
|
||||
' return k',
|
||||
' end',
|
||||
' end',
|
||||
' return 0',
|
||||
'end']);
|
||||
} else {
|
||||
functionName = Blockly.Lua.provideFunction_(
|
||||
'last_index',
|
||||
['function ' + Blockly.Lua.FUNCTION_NAME_PLACEHOLDER_ + '(t, elem)',
|
||||
' for i = #t, 1, -1 do',
|
||||
' if t[i] == elem then',
|
||||
' return i',
|
||||
' end',
|
||||
' end',
|
||||
' return 0',
|
||||
'end']);
|
||||
}
|
||||
var code = functionName + '(' + argument1 + ', ' + argument0 + ')';
|
||||
return [code, Blockly.Lua.ORDER_HIGH];
|
||||
};
|
||||
|
||||
/**
|
||||
* Returns an expression calculating the index into a list.
|
||||
* @private
|
||||
* @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} Index expression.
|
||||
*/
|
||||
Blockly.Lua.lists.getIndex_ = function(listname, where, opt_at) {
|
||||
if (where == 'FIRST') {
|
||||
return 1;
|
||||
} else if (where == 'FROM_END') {
|
||||
return '#' + listname + ' + 1 - ' + opt_at;
|
||||
} else if (where == 'LAST') {
|
||||
return '#' + listname;
|
||||
} else if (where == 'RANDOM') {
|
||||
return 'math.random(#' + listname + ')';
|
||||
} else {
|
||||
return opt_at;
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* Counter for generating unique symbols.
|
||||
* @private
|
||||
* @type {number}
|
||||
*/
|
||||
Blockly.Lua.lists.gensym_counter_ = 0;
|
||||
|
||||
/**
|
||||
* Generate a unique symbol.
|
||||
* @private
|
||||
* @return {string} unique symbol, eg 'G123'
|
||||
*/
|
||||
Blockly.Lua.lists.gensym_ = function() {
|
||||
return 'G' + Blockly.Lua.lists.gensym_counter_++;
|
||||
};
|
||||
|
||||
Blockly.Lua['lists_getIndex'] = function(block) {
|
||||
// Get element at index.
|
||||
// Note: Until January 2013 this block did not have MODE or WHERE inputs.
|
||||
var mode = block.getTitleValue('MODE') || 'GET';
|
||||
var where = block.getTitleValue('WHERE') || 'FROM_START';
|
||||
var at = Blockly.Lua.valueToCode(block, 'AT',
|
||||
Blockly.Lua.ORDER_ADDITIVE) || '1';
|
||||
var list = Blockly.Lua.valueToCode(block, 'VALUE',
|
||||
Blockly.Lua.ORDER_HIGH) || '({})';
|
||||
var getIndex_ = Blockly.Lua.lists.getIndex_;
|
||||
var gensym_ = Blockly.Lua.lists.gensym_;
|
||||
|
||||
// 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+$/)) {
|
||||
// `list` is an expression, so we may not evaluate it more than once.
|
||||
if (mode == 'REMOVE') {
|
||||
// We can use multiple statements.
|
||||
var listVar = Blockly.Lua.variableDB_.getDistinctName(
|
||||
'tmp_list', Blockly.Variables.NAME_TYPE);
|
||||
var code = listVar + ' = ' + list + '\n' +
|
||||
'table.remove(' + listVar + ', ' + getIndex_(listVar, where, at) +
|
||||
')\n';
|
||||
return code;
|
||||
} else {
|
||||
// We need to create a procedure to avoid reevaluating values.
|
||||
if (mode == 'GET') {
|
||||
// Note that getIndex_() ignores `at` when `where` == 'LAST' or
|
||||
// 'RANDOM', so we only need one procedure for each of those 'where'
|
||||
// values. The value for 'FROM_END' depends on `at`, so we will
|
||||
// generate a unique procedure (name) each time.
|
||||
var functionName = Blockly.Lua.provideFunction_(
|
||||
'list_get_' + where.toLowerCase() +
|
||||
(where == 'FROM_END' ? '_' + gensym_() : ''),
|
||||
['function ' + Blockly.Lua.FUNCTION_NAME_PLACEHOLDER_ + '(t)',
|
||||
' return t[' + getIndex_('t', where, at) + ']',
|
||||
'end']);
|
||||
} else { // mode == 'GET_REMOVE'
|
||||
// We need to create a procedure.
|
||||
var functionName = Blockly.Lua.provideFunction_(
|
||||
'list_remove_' + where.toLowerCase() +
|
||||
(where == 'FROM_END' ? '_' + gensym_() : ''),
|
||||
['function ' + Blockly.Lua.FUNCTION_NAME_PLACEHOLDER_ + '(t)',
|
||||
' return table.remove(t, ' + getIndex_('t', where, at) + ')',
|
||||
'end']);
|
||||
}
|
||||
var code = functionName + '(' + list + ')';
|
||||
return [code, Blockly.Lua.ORDER_HIGH];
|
||||
}
|
||||
} else {
|
||||
// Either `list` is a simple variable, or we only need to refer to `list`
|
||||
// once.
|
||||
if (mode == 'GET') {
|
||||
var code = list + '[' + getIndex_(list, where, at) + ']';
|
||||
return [code, Blockly.Lua.ORDER_HIGH];
|
||||
} else {
|
||||
var code = 'table.remove(' + list + ', ' + getIndex_(list, where, at) +
|
||||
')';
|
||||
if (mode == 'GET_REMOVE') {
|
||||
return [code, Blockly.Lua.ORDER_HIGH];
|
||||
} else { // `mode` == 'REMOVE'
|
||||
return code + '\n';
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
Blockly.Lua['lists_setIndex'] = function(block) {
|
||||
// Set element at index.
|
||||
// Note: Until February 2013 this block did not have MODE or WHERE inputs.
|
||||
var list = Blockly.Lua.valueToCode(block, 'LIST',
|
||||
Blockly.Lua.ORDER_HIGH) || '({})';
|
||||
var mode = block.getFieldValue('MODE') || 'SET';
|
||||
var where = block.getFieldValue('WHERE') || 'FROM_START';
|
||||
var at = Blockly.Lua.valueToCode(block, 'AT',
|
||||
Blockly.Lua.ORDER_ADDITIVE) || '1';
|
||||
var value = Blockly.Lua.valueToCode(block, 'TO',
|
||||
Blockly.Lua.ORDER_NONE) || 'None';
|
||||
var getIndex_ = Blockly.Lua.lists.getIndex_;
|
||||
|
||||
// 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+$/)) {
|
||||
// `list` is an expression, so we may not evaluate it more than once.
|
||||
if (where == 'RANDOM' || where == 'LAST') {
|
||||
// In these cases, `at` is implicit. getIndex_() ignores its value.
|
||||
if (mode == 'SET') {
|
||||
var functionName = Blockly.Lua.provideFunction_(
|
||||
'list_set_' + where.toLowerCase(),
|
||||
['function ' + Blockly.Lua.FUNCTION_NAME_PLACEHOLDER_ + '(t, val)',
|
||||
' t[' + getIndex_('t', where, at) + '] = val',
|
||||
'end']);
|
||||
} else { // `mode` == 'INSERT'
|
||||
var functionName = Blockly.Lua.provideFunction_(
|
||||
'list_insert_' + where.toLowerCase(),
|
||||
['function ' + Blockly.Lua.FUNCTION_NAME_PLACEHOLDER_ + '(t, val)',
|
||||
' table.insert(t, ' +
|
||||
// LAST is a special case, because we want to insert
|
||||
// *after* not *before*, the existing last element.
|
||||
getIndex_('t', where, at) + (where == 'LAST' ? ' + 1' : '') +
|
||||
', val)',
|
||||
'end']);
|
||||
}
|
||||
var code = functionName + '(' + list + ', ' + value + ')\n';
|
||||
return code;
|
||||
} else { // `where` = 'FROM_END'
|
||||
if (mode == 'SET') {
|
||||
var functionName = Blockly.Lua.provideFunction_(
|
||||
'list_set_from_end',
|
||||
['function ' + Blockly.Lua.FUNCTION_NAME_PLACEHOLDER_ +
|
||||
'(t, index, val)',
|
||||
' t[#t + 1 - index] = val',
|
||||
'end']);
|
||||
} else { // `mode` == 'INSERT'
|
||||
var functionName = Blockly.Lua.provideFunction_(
|
||||
'list_insert_from_end',
|
||||
['function ' + Blockly.Lua.FUNCTION_NAME_PLACEHOLDER_ +
|
||||
'(t, index, val)',
|
||||
' table.insert(t, #t + 1 - index, val)',
|
||||
'end']);
|
||||
}
|
||||
var code = functionName + '(' + list + ', ' + at + ', ' + value + ')\n';
|
||||
return code;
|
||||
}
|
||||
} else {
|
||||
// It's okay to have multiple references to the list.
|
||||
if (mode == 'SET') {
|
||||
var code = list + '[' + getIndex_(list, where, at) + '] = ' + value;
|
||||
} else { // `mode` == 'INSERT'
|
||||
// LAST is a special case, because we want to insert
|
||||
// *after* not *before*, the existing last element.
|
||||
var code = 'table.insert(' + list + ', ' +
|
||||
(getIndex_(list, where, at) + (where == 'LAST' ? ' + 1' : '')) +
|
||||
', ' + value + ')';
|
||||
}
|
||||
return code + '\n';
|
||||
}
|
||||
};
|
||||
|
||||
Blockly.Lua['lists_getSublist'] = function(block) {
|
||||
// Get sublist.
|
||||
var list = Blockly.Lua.valueToCode(block, 'LIST',
|
||||
Blockly.Lua.ORDER_HIGH) || '({})';
|
||||
var where1 = block.getFieldValue('WHERE1');
|
||||
var where2 = block.getFieldValue('WHERE2');
|
||||
var at1 = Blockly.Lua.valueToCode(block, 'AT1',
|
||||
Blockly.Lua.ORDER_ADDITIVE) || '1';
|
||||
var at2 = Blockly.Lua.valueToCode(block, 'AT2',
|
||||
Blockly.Lua.ORDER_ADDITIVE) || '1';
|
||||
var getIndex_ = Blockly.Lua.lists.getIndex_;
|
||||
|
||||
var functionName = Blockly.Lua.provideFunction_(
|
||||
'list_sublist_' + Blockly.Lua.lists.gensym_(),
|
||||
['function ' + Blockly.Lua.FUNCTION_NAME_PLACEHOLDER_ + '(source)',
|
||||
' local t = {}',
|
||||
' local start = ' + getIndex_('source', where1, at1),
|
||||
' local finish = ' + getIndex_('source', where2, at2),
|
||||
' for i = start, finish do',
|
||||
' table.insert(t, source[i])',
|
||||
' end',
|
||||
' return t',
|
||||
'end']);
|
||||
var code = functionName + '(' + list + ')';
|
||||
return [code, Blockly.Lua.ORDER_HIGH];
|
||||
};
|
||||
|
||||
Blockly.Lua['lists_split'] = function(block) {
|
||||
// Block for splitting text into a list, or joining a list into text.
|
||||
var value_input = Blockly.Lua.valueToCode(block, 'INPUT',
|
||||
Blockly.Lua.ORDER_NONE);
|
||||
var value_delim = Blockly.Lua.valueToCode(block, 'DELIM',
|
||||
Blockly.Lua.ORDER_NONE) || '\'\'';
|
||||
var mode = block.getFieldValue('MODE');
|
||||
var functionName;
|
||||
if (mode == 'SPLIT') {
|
||||
if (!value_input) {
|
||||
value_input = '\'\'';
|
||||
}
|
||||
functionName = Blockly.Lua.provideFunction_(
|
||||
'list_string_split',
|
||||
['function ' + Blockly.Lua.FUNCTION_NAME_PLACEHOLDER_ +
|
||||
'(input, delim)',
|
||||
' local t = {}',
|
||||
' local pos = 1',
|
||||
' while true do',
|
||||
' next_delim = string.find(input, delim, pos)',
|
||||
' if next_delim == nil then',
|
||||
' table.insert(t, string.sub(input, pos))',
|
||||
' break',
|
||||
' else',
|
||||
' table.insert(t, string.sub(input, pos, next_delim-1))',
|
||||
' pos = next_delim + #delim',
|
||||
' end',
|
||||
' end',
|
||||
' return t',
|
||||
'end']);
|
||||
} else if (mode == 'JOIN') {
|
||||
if (!value_input) {
|
||||
value_input = '({})';
|
||||
}
|
||||
functionName = 'table.concat';
|
||||
} else {
|
||||
throw 'Unknown mode: ' + mode;
|
||||
}
|
||||
var code = functionName + '(' + value_input + ', ' + value_delim + ')';
|
||||
return [code, Blockly.Lua.ORDER_HIGH];
|
||||
};
|
||||
125
generators/lua/logic.js
Normal file
125
generators/lua/logic.js
Normal file
@@ -0,0 +1,125 @@
|
||||
/**
|
||||
* @license
|
||||
* Visual Blocks Language
|
||||
*
|
||||
* Copyright 2016 Google Inc.
|
||||
* https://developers.google.com/blockly/
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
/**
|
||||
* @fileoverview Generating Lua for logic blocks.
|
||||
* @author rodrigoq@google.com (Rodrigo Queiro)
|
||||
*/
|
||||
'use strict';
|
||||
|
||||
goog.provide('Blockly.Lua.logic');
|
||||
|
||||
goog.require('Blockly.Lua');
|
||||
|
||||
|
||||
Blockly.Lua['controls_if'] = function(block) {
|
||||
// If/elseif/else condition.
|
||||
var n = 0;
|
||||
var argument = Blockly.Lua.valueToCode(block, 'IF' + n,
|
||||
Blockly.Lua.ORDER_NONE) || 'false';
|
||||
var branch = Blockly.Lua.statementToCode(block, 'DO' + n);
|
||||
var code = 'if ' + argument + ' then\n' + branch;
|
||||
for (n = 1; n <= block.elseifCount_; n++) {
|
||||
argument = Blockly.Lua.valueToCode(block, 'IF' + n,
|
||||
Blockly.Lua.ORDER_NONE) || 'false';
|
||||
branch = Blockly.Lua.statementToCode(block, 'DO' + n);
|
||||
code += ' elseif ' + argument + ' then\n' + branch;
|
||||
}
|
||||
if (block.elseCount_) {
|
||||
branch = Blockly.Lua.statementToCode(block, 'ELSE');
|
||||
code += ' else\n' + branch;
|
||||
}
|
||||
return code + 'end\n';
|
||||
};
|
||||
|
||||
Blockly.Lua['logic_compare'] = function(block) {
|
||||
// Comparison operator.
|
||||
var OPERATORS = {
|
||||
'EQ': '==',
|
||||
'NEQ': '~=',
|
||||
'LT': '<',
|
||||
'LTE': '<=',
|
||||
'GT': '>',
|
||||
'GTE': '>='
|
||||
};
|
||||
var operator = OPERATORS[block.getFieldValue('OP')];
|
||||
var argument0 = Blockly.Lua.valueToCode(block, 'A',
|
||||
Blockly.Lua.ORDER_RELATIONAL) || '0';
|
||||
var argument1 = Blockly.Lua.valueToCode(block, 'B',
|
||||
Blockly.Lua.ORDER_RELATIONAL) || '0';
|
||||
var code = argument0 + ' ' + operator + ' ' + argument1;
|
||||
return [code, Blockly.Lua.ORDER_RELATIONAL];
|
||||
};
|
||||
|
||||
Blockly.Lua['logic_operation'] = function(block) {
|
||||
// Operations 'and', 'or'.
|
||||
var operator = (block.getFieldValue('OP') == 'AND') ? 'and' : 'or';
|
||||
var order = (operator == 'and') ? Blockly.Lua.ORDER_AND :
|
||||
Blockly.Lua.ORDER_OR;
|
||||
var argument0 = Blockly.Lua.valueToCode(block, 'A', order);
|
||||
var argument1 = Blockly.Lua.valueToCode(block, 'B', order);
|
||||
if (!argument0 && !argument1) {
|
||||
// If there are no arguments, then the return value is false.
|
||||
argument0 = 'false';
|
||||
argument1 = 'false';
|
||||
} else {
|
||||
// Single missing arguments have no effect on the return value.
|
||||
var defaultArgument = (operator == 'and') ? 'true' : 'false';
|
||||
if (!argument0) {
|
||||
argument0 = defaultArgument;
|
||||
}
|
||||
if (!argument1) {
|
||||
argument1 = defaultArgument;
|
||||
}
|
||||
}
|
||||
var code = argument0 + ' ' + operator + ' ' + argument1;
|
||||
return [code, order];
|
||||
};
|
||||
|
||||
Blockly.Lua['logic_negate'] = function(block) {
|
||||
// Negation.
|
||||
var argument0 = Blockly.Lua.valueToCode(block, 'BOOL',
|
||||
Blockly.Lua.ORDER_UNARY) || 'true';
|
||||
var code = 'not ' + argument0;
|
||||
return [code, Blockly.Lua.ORDER_UNARY];
|
||||
};
|
||||
|
||||
Blockly.Lua['logic_boolean'] = function(block) {
|
||||
// Boolean values true and false.
|
||||
var code = (block.getFieldValue('BOOL') == 'TRUE') ? 'true' : 'false';
|
||||
return [code, Blockly.Lua.ORDER_ATOMIC];
|
||||
};
|
||||
|
||||
Blockly.Lua['logic_null'] = function(block) {
|
||||
// Null data type.
|
||||
return ['nil', Blockly.Lua.ORDER_ATOMIC];
|
||||
};
|
||||
|
||||
Blockly.Lua['logic_ternary'] = function(block) {
|
||||
// Ternary operator.
|
||||
var value_if = Blockly.Lua.valueToCode(block, 'IF',
|
||||
Blockly.Lua.ORDER_AND) || 'false';
|
||||
var value_then = Blockly.Lua.valueToCode(block, 'THEN',
|
||||
Blockly.Lua.ORDER_AND) || 'nil';
|
||||
var value_else = Blockly.Lua.valueToCode(block, 'ELSE',
|
||||
Blockly.Lua.ORDER_OR) || 'nil';
|
||||
var code = value_if + ' and ' + value_then + ' or ' + value_else;
|
||||
return [code, Blockly.Lua.ORDER_OR];
|
||||
};
|
||||
166
generators/lua/loops.js
Normal file
166
generators/lua/loops.js
Normal file
@@ -0,0 +1,166 @@
|
||||
/**
|
||||
* @license
|
||||
* Visual Blocks Language
|
||||
*
|
||||
* Copyright 2016 Google Inc.
|
||||
* https://developers.google.com/blockly/
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
/**
|
||||
* @fileoverview Generating Lua for loop blocks.
|
||||
* @author rodrigoq@google.com (Rodrigo Queiro)
|
||||
*/
|
||||
'use strict';
|
||||
|
||||
goog.provide('Blockly.Lua.loops');
|
||||
|
||||
goog.require('Blockly.Lua');
|
||||
|
||||
|
||||
/**
|
||||
* 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}
|
||||
*/
|
||||
Blockly.Lua.CONTINUE_STATEMENT = 'goto continue\n';
|
||||
|
||||
/**
|
||||
* If the loop body contains a "goto continue" statement, add a continue label
|
||||
* to the loop body. Slightly inefficient, as continue labels will be generated
|
||||
* in all outer loops, but this is safer than duplicating the logic of
|
||||
* blockToCode.
|
||||
*
|
||||
* @param {string} branch Generated code of the loop body
|
||||
* @return {string} Generated label or '' if unnecessary
|
||||
*/
|
||||
Blockly.Lua.addContinueLabel = function(branch) {
|
||||
if (branch.indexOf(Blockly.Lua.CONTINUE_STATEMENT) > -1) {
|
||||
return branch + Blockly.Lua.INDENT + '::continue::\n';
|
||||
} else {
|
||||
return branch;
|
||||
}
|
||||
};
|
||||
|
||||
Blockly.Lua['controls_repeat'] = function(block) {
|
||||
// Repeat n times (internal number).
|
||||
var repeats = parseInt(block.getFieldValue('TIMES'), 10);
|
||||
var branch = Blockly.Lua.statementToCode(block, 'DO') || '';
|
||||
branch = Blockly.Lua.addContinueLabel(branch);
|
||||
var loopVar = Blockly.Lua.variableDB_.getDistinctName(
|
||||
'count', Blockly.Variables.NAME_TYPE);
|
||||
var code = 'for ' + loopVar + ' = 1, ' + repeats + ' do\n' + branch + 'end\n';
|
||||
return code;
|
||||
};
|
||||
|
||||
Blockly.Lua['controls_repeat_ext'] = function(block) {
|
||||
// Repeat n times (external number).
|
||||
var repeats = Blockly.Lua.valueToCode(block, 'TIMES',
|
||||
Blockly.Lua.ORDER_NONE) || '0';
|
||||
if (Blockly.isNumber(repeats)) {
|
||||
repeats = parseInt(repeats, 10);
|
||||
} else {
|
||||
repeats = 'math.floor(' + repeats + ')';
|
||||
}
|
||||
var branch = Blockly.Lua.statementToCode(block, 'DO') || '\n';
|
||||
branch = Blockly.Lua.addContinueLabel(branch);
|
||||
var loopVar = Blockly.Lua.variableDB_.getDistinctName(
|
||||
'count', Blockly.Variables.NAME_TYPE);
|
||||
var code = 'for ' + loopVar + ' = 1, ' + repeats + ' do\n' +
|
||||
branch + 'end\n';
|
||||
return code;
|
||||
};
|
||||
|
||||
Blockly.Lua['controls_whileUntil'] = function(block) {
|
||||
// Do while/until loop.
|
||||
var until = block.getFieldValue('MODE') == 'UNTIL';
|
||||
var argument0 = Blockly.Lua.valueToCode(block, 'BOOL',
|
||||
until ? Blockly.Lua.ORDER_UNARY :
|
||||
Blockly.Lua.ORDER_NONE) || 'false';
|
||||
var branch = Blockly.Lua.statementToCode(block, 'DO') || '\n';
|
||||
branch = Blockly.Lua.addLoopTrap(branch, block.id);
|
||||
branch = Blockly.Lua.addContinueLabel(branch);
|
||||
if (until) {
|
||||
argument0 = 'not ' + argument0;
|
||||
}
|
||||
return 'while ' + argument0 + ' do\n' + branch + 'end\n';
|
||||
};
|
||||
|
||||
Blockly.Lua['controls_for'] = function(block) {
|
||||
// For loop.
|
||||
var variable0 = Blockly.Lua.variableDB_.getName(
|
||||
block.getFieldValue('VAR'), Blockly.Variables.NAME_TYPE);
|
||||
var startVar = Blockly.Lua.valueToCode(block, 'FROM',
|
||||
Blockly.Lua.ORDER_NONE) || '0';
|
||||
var endVar = Blockly.Lua.valueToCode(block, 'TO',
|
||||
Blockly.Lua.ORDER_NONE) || '0';
|
||||
var increment = Blockly.Lua.valueToCode(block, 'BY',
|
||||
Blockly.Lua.ORDER_NONE) || '1';
|
||||
var branch = Blockly.Lua.statementToCode(block, 'DO') || '\n';
|
||||
branch = Blockly.Lua.addLoopTrap(branch, block.id);
|
||||
branch = Blockly.Lua.addContinueLabel(branch);
|
||||
var code = '';
|
||||
var incValue;
|
||||
if (Blockly.isNumber(startVar) && Blockly.isNumber(endVar) &&
|
||||
Blockly.isNumber(increment)) {
|
||||
// All arguments are simple numbers.
|
||||
var up = parseFloat(startVar) <= parseFloat(endVar);
|
||||
var step = Math.abs(parseFloat(increment));
|
||||
incValue = (up ? '' : '-') + step;
|
||||
} else {
|
||||
code = '';
|
||||
// Determine loop direction at start, in case one of the bounds
|
||||
// changes during loop execution.
|
||||
incValue = Blockly.Lua.variableDB_.getDistinctName(
|
||||
variable0 + '_inc', Blockly.Variables.NAME_TYPE);
|
||||
code += incValue + ' = ';
|
||||
if (Blockly.isNumber(increment)) {
|
||||
code += Math.abs(increment) + '\n';
|
||||
} else {
|
||||
code += 'math.abs(' + increment + ')\n';
|
||||
}
|
||||
code += 'if (' + startVar + ') > (' + endVar + ') then\n';
|
||||
code += Blockly.Lua.INDENT + incValue + ' = -' + incValue + '\n';
|
||||
code += 'end\n';
|
||||
}
|
||||
code += 'for ' + variable0 + ' = ' + startVar + ', ' + endVar +
|
||||
', ' + incValue;
|
||||
code += ' do\n' + branch + 'end\n';
|
||||
return code;
|
||||
};
|
||||
|
||||
Blockly.Lua['controls_forEach'] = function(block) {
|
||||
// For each loop.
|
||||
var variable0 = Blockly.Lua.variableDB_.getName(
|
||||
block.getFieldValue('VAR'), Blockly.Variables.NAME_TYPE);
|
||||
var argument0 = Blockly.Lua.valueToCode(block, 'LIST',
|
||||
Blockly.Lua.ORDER_NONE) || '{}';
|
||||
var branch = Blockly.Lua.statementToCode(block, 'DO') || '\n';
|
||||
branch = Blockly.Lua.addContinueLabel(branch);
|
||||
var code = 'for _, ' + variable0 + ' in ipairs(' + argument0 + ') do \n' +
|
||||
branch + 'end\n';
|
||||
return code;
|
||||
};
|
||||
|
||||
Blockly.Lua['controls_flow_statements'] = function(block) {
|
||||
// Flow statements: continue, break.
|
||||
switch (block.getFieldValue('FLOW')) {
|
||||
case 'BREAK':
|
||||
return 'break\n';
|
||||
case 'CONTINUE':
|
||||
return Blockly.Lua.CONTINUE_STATEMENT;
|
||||
}
|
||||
throw 'Unknown flow statement.';
|
||||
};
|
||||
425
generators/lua/math.js
Normal file
425
generators/lua/math.js
Normal file
@@ -0,0 +1,425 @@
|
||||
/**
|
||||
* @license
|
||||
* Visual Blocks Language
|
||||
*
|
||||
* Copyright 2016 Google Inc.
|
||||
* https://developers.google.com/blockly/
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
/**
|
||||
* @fileoverview Generating Lua for math blocks.
|
||||
* @author rodrigoq@google.com (Rodrigo Queiro)
|
||||
*/
|
||||
'use strict';
|
||||
|
||||
goog.provide('Blockly.Lua.math');
|
||||
|
||||
goog.require('Blockly.Lua');
|
||||
|
||||
|
||||
Blockly.Lua['math_number'] = function(block) {
|
||||
// Numeric value.
|
||||
var code = parseFloat(block.getFieldValue('NUM'));
|
||||
var order = code < 0 ? Blockly.Lua.ORDER_UNARY :
|
||||
Blockly.Lua.ORDER_ATOMIC;
|
||||
return [code, order];
|
||||
};
|
||||
|
||||
Blockly.Lua['math_arithmetic'] = function(block) {
|
||||
// Basic arithmetic operators, and power.
|
||||
var OPERATORS = {
|
||||
ADD: [' + ', Blockly.Lua.ORDER_ADDITIVE],
|
||||
MINUS: [' - ', Blockly.Lua.ORDER_ADDITIVE],
|
||||
MULTIPLY: [' * ', Blockly.Lua.ORDER_MULTIPLICATIVE],
|
||||
DIVIDE: [' / ', Blockly.Lua.ORDER_MULTIPLICATIVE],
|
||||
POWER: [' ^ ', Blockly.Lua.ORDER_EXPONENTIATION]
|
||||
};
|
||||
var tuple = OPERATORS[block.getFieldValue('OP')];
|
||||
var operator = tuple[0];
|
||||
var order = tuple[1];
|
||||
var argument0 = Blockly.Lua.valueToCode(block, 'A', order) || '0';
|
||||
var argument1 = Blockly.Lua.valueToCode(block, 'B', order) || '0';
|
||||
var code = argument0 + operator + argument1;
|
||||
return [code, order];
|
||||
};
|
||||
|
||||
Blockly.Lua['math_single'] = function(block) {
|
||||
// Math operators with single operand.
|
||||
var operator = block.getFieldValue('OP');
|
||||
var code;
|
||||
var arg;
|
||||
if (operator == 'NEG') {
|
||||
// Negation is a special case given its different operator precedence.
|
||||
arg = Blockly.Lua.valueToCode(block, 'NUM',
|
||||
Blockly.Lua.ORDER_UNARY) || '0';
|
||||
return ['-' + arg, Blockly.Lua.ORDER_UNARY];
|
||||
}
|
||||
if (operator == 'SIN' || operator == 'COS' || operator == 'TAN') {
|
||||
arg = Blockly.Lua.valueToCode(block, 'NUM',
|
||||
Blockly.Lua.ORDER_MULTIPLICATIVE) || '0';
|
||||
} else {
|
||||
arg = Blockly.Lua.valueToCode(block, 'NUM',
|
||||
Blockly.Lua.ORDER_NONE) || '0';
|
||||
}
|
||||
switch (operator) {
|
||||
case 'ABS':
|
||||
code = 'math.abs(' + arg + ')';
|
||||
break;
|
||||
case 'ROOT':
|
||||
code = 'math.sqrt(' + arg + ')';
|
||||
break;
|
||||
case 'LN':
|
||||
code = 'math.log(' + arg + ')';
|
||||
break;
|
||||
case 'LOG10':
|
||||
code = 'math.log10(' + arg + ')';
|
||||
break;
|
||||
case 'EXP':
|
||||
code = 'math.exp(' + arg + ')';
|
||||
break;
|
||||
case 'POW10':
|
||||
code = 'math.pow(10,' + arg + ')';
|
||||
break;
|
||||
case 'ROUND':
|
||||
// This rounds up. Blockly does not specify rounding direction.
|
||||
code = 'math.floor(' + arg + ' + .5)';
|
||||
break;
|
||||
case 'ROUNDUP':
|
||||
code = 'math.ceil(' + arg + ')';
|
||||
break;
|
||||
case 'ROUNDDOWN':
|
||||
code = 'math.floor(' + arg + ')';
|
||||
break;
|
||||
case 'SIN':
|
||||
code = 'math.sin(math.rad(' + arg + '))';
|
||||
break;
|
||||
case 'COS':
|
||||
code = 'math.cos(math.rad(' + arg + '))';
|
||||
break;
|
||||
case 'TAN':
|
||||
code = 'math.tan(math.rad(' + arg + '))';
|
||||
break;
|
||||
case 'ASIN':
|
||||
code = 'math.deg(math.asin(' + arg + '))';
|
||||
break;
|
||||
case 'ACOS':
|
||||
code = 'math.deg(math.acos(' + arg + '))';
|
||||
break;
|
||||
case 'ATAN':
|
||||
code = 'math.deg(math.atan(' + arg + '))';
|
||||
break;
|
||||
default:
|
||||
throw 'Unknown math operator: ' + operator;
|
||||
}
|
||||
return [code, Blockly.Lua.ORDER_HIGH];
|
||||
};
|
||||
|
||||
Blockly.Lua['math_constant'] = function(block) {
|
||||
// Constants: PI, E, the Golden Ratio, sqrt(2), 1/sqrt(2), INFINITY.
|
||||
var CONSTANTS = {
|
||||
PI: ['math.pi', Blockly.Lua.ORDER_HIGH],
|
||||
E: ['math.exp(1)', Blockly.Lua.ORDER_HIGH],
|
||||
GOLDEN_RATIO: ['(1 + math.sqrt(5)) / 2', Blockly.Lua.ORDER_MULTIPLICATIVE],
|
||||
SQRT2: ['math.sqrt(2)', Blockly.Lua.ORDER_HIGH],
|
||||
SQRT1_2: ['math.sqrt(1 / 2)', Blockly.Lua.ORDER_HIGH],
|
||||
INFINITY: ['math.huge', Blockly.Lua.ORDER_HIGH]
|
||||
};
|
||||
return CONSTANTS[block.getFieldValue('CONSTANT')];
|
||||
};
|
||||
|
||||
Blockly.Lua['math_number_property'] = function(block) {
|
||||
// Check if a number is even, odd, prime, whole, positive, or negative
|
||||
// or if it is divisible by certain number. Returns true or false.
|
||||
var number_to_check = Blockly.Lua.valueToCode(block, 'NUMBER_TO_CHECK',
|
||||
Blockly.Lua.ORDER_MULTIPLICATIVE) || '0';
|
||||
var dropdown_property = block.getFieldValue('PROPERTY');
|
||||
var code;
|
||||
if (dropdown_property == 'PRIME') {
|
||||
// Prime is a special case as it is not a one-liner test.
|
||||
var functionName = Blockly.Lua.provideFunction_(
|
||||
'math_isPrime',
|
||||
['function ' + Blockly.Lua.FUNCTION_NAME_PLACEHOLDER_ + '(n)',
|
||||
' -- https://en.wikipedia.org/wiki/Primality_test#Naive_methods',
|
||||
' if n == 2 or n == 3 then',
|
||||
' return true',
|
||||
' end',
|
||||
' -- False if n is NaN, negative, is 1, or not whole.',
|
||||
' -- And false if n is divisible by 2 or 3.',
|
||||
' if not(n > 1) or n % 1 ~= 0 or n % 2 == 0 or n % 3 == 0 then',
|
||||
' return false',
|
||||
' end',
|
||||
' -- Check all the numbers of form 6k +/- 1, up to sqrt(n).',
|
||||
' for x = 6, math.sqrt(n) + 1.5, 6 do',
|
||||
' if n % (x - 1) == 0 or n % (x + 1) == 0 then',
|
||||
' return false',
|
||||
' end',
|
||||
' end',
|
||||
' return true',
|
||||
'end']);
|
||||
code = functionName + '(' + number_to_check + ')';
|
||||
return [code, Blockly.Lua.ORDER_HIGH];
|
||||
}
|
||||
switch (dropdown_property) {
|
||||
case 'EVEN':
|
||||
code = number_to_check + ' % 2 == 0';
|
||||
break;
|
||||
case 'ODD':
|
||||
code = number_to_check + ' % 2 == 1';
|
||||
break;
|
||||
case 'WHOLE':
|
||||
code = number_to_check + ' % 1 == 0';
|
||||
break;
|
||||
case 'POSITIVE':
|
||||
code = number_to_check + ' > 0';
|
||||
break;
|
||||
case 'NEGATIVE':
|
||||
code = number_to_check + ' < 0';
|
||||
break;
|
||||
case 'DIVISIBLE_BY':
|
||||
var divisor = Blockly.Lua.valueToCode(block, 'DIVISOR',
|
||||
Blockly.Lua.ORDER_MULTIPLICATIVE);
|
||||
// If 'divisor' is some code that evals to 0, Lua will produce a nan.
|
||||
// Let's produce nil if we can determine this at compile-time.
|
||||
if (!divisor || divisor == '0') {
|
||||
return ['nil', Blockly.Lua.ORDER_ATOMIC];
|
||||
}
|
||||
// The normal trick to implement ?: with and/or doesn't work here:
|
||||
// divisor == 0 and nil or number_to_check % divisor == 0
|
||||
// because nil is false, so allow a runtime failure. :-(
|
||||
code = number_to_check + ' % ' + divisor + ' == 0';
|
||||
break;
|
||||
}
|
||||
return [code, Blockly.Lua.ORDER_RELATIONAL];
|
||||
};
|
||||
|
||||
Blockly.Lua['math_change'] = function(block) {
|
||||
// Add to a variable in place.
|
||||
var argument0 = Blockly.Lua.valueToCode(block, 'DELTA',
|
||||
Blockly.Lua.ORDER_ADDITIVE) || '0';
|
||||
var varName = Blockly.Lua.variableDB_.getName(
|
||||
block.getFieldValue('VAR'), Blockly.Variables.NAME_TYPE);
|
||||
return varName + ' = ' + varName + ' + ' + argument0 + '\n';
|
||||
};
|
||||
|
||||
// Rounding functions have a single operand.
|
||||
Blockly.Lua['math_round'] = Blockly.Lua['math_single'];
|
||||
// Trigonometry functions have a single operand.
|
||||
Blockly.Lua['math_trig'] = Blockly.Lua['math_single'];
|
||||
|
||||
Blockly.Lua['math_on_list'] = function(block) {
|
||||
// Math functions for lists.
|
||||
var func = block.getFieldValue('OP');
|
||||
var list = Blockly.Lua.valueToCode(block, 'LIST',
|
||||
Blockly.Lua.ORDER_NONE) || '{}';
|
||||
var functionName;
|
||||
|
||||
// Functions needed in more than one case.
|
||||
function provideSum() {
|
||||
return Blockly.Lua.provideFunction_(
|
||||
'math_sum',
|
||||
['function ' + Blockly.Lua.FUNCTION_NAME_PLACEHOLDER_ + '(t)',
|
||||
' local result = 0',
|
||||
' for _, v in ipairs(t) do',
|
||||
' result = result + v',
|
||||
' end',
|
||||
' return result',
|
||||
'end']);
|
||||
}
|
||||
|
||||
switch (func) {
|
||||
case 'SUM':
|
||||
functionName = provideSum();
|
||||
break;
|
||||
|
||||
case 'MIN':
|
||||
// Returns 0 for the empty list.
|
||||
functionName = Blockly.Lua.provideFunction_(
|
||||
'math_min',
|
||||
['function ' + Blockly.Lua.FUNCTION_NAME_PLACEHOLDER_ + '(t)',
|
||||
' if #t == 0 then',
|
||||
' return 0',
|
||||
' end',
|
||||
' local result = math.huge',
|
||||
' for _, v in ipairs(t) do',
|
||||
' if v < result then',
|
||||
' result = v',
|
||||
' end',
|
||||
' end',
|
||||
' return result',
|
||||
'end']);
|
||||
break;
|
||||
|
||||
case 'AVERAGE':
|
||||
// Returns 0 for the empty list.
|
||||
functionName = Blockly.Lua.provideFunction_(
|
||||
'math_average',
|
||||
['function ' + Blockly.Lua.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 = Blockly.Lua.provideFunction_(
|
||||
'math_max',
|
||||
['function ' + Blockly.Lua.FUNCTION_NAME_PLACEHOLDER_ + '(t)',
|
||||
' if #t == 0 then',
|
||||
' return 0',
|
||||
' end',
|
||||
' local result = -math.huge',
|
||||
' for _, v in ipairs(t) do',
|
||||
' if v > result then',
|
||||
' result = v',
|
||||
' end',
|
||||
' end',
|
||||
' return result',
|
||||
'end']);
|
||||
break;
|
||||
|
||||
case 'MEDIAN':
|
||||
functionName = Blockly.Lua.provideFunction_(
|
||||
'math_median',
|
||||
// This operation excludes non-numbers.
|
||||
['function ' + Blockly.Lua.FUNCTION_NAME_PLACEHOLDER_ + '(t)',
|
||||
' -- Source: http://lua-users.org/wiki/SimpleStats',
|
||||
' if #t == 0 then',
|
||||
' return 0',
|
||||
' end',
|
||||
' local temp={}',
|
||||
' for _, v in ipairs(t) do',
|
||||
' if type(v) == "number" then',
|
||||
' table.insert(temp, v)',
|
||||
' end',
|
||||
' end',
|
||||
' table.sort(temp)',
|
||||
' if #temp % 2 == 0 then',
|
||||
' return (temp[#temp/2] + temp[(#temp/2)+1]) / 2',
|
||||
' else',
|
||||
' return temp[math.ceil(#temp/2)]',
|
||||
' end',
|
||||
'end']);
|
||||
break;
|
||||
|
||||
case 'MODE':
|
||||
functionName = Blockly.Lua.provideFunction_(
|
||||
'math_modes',
|
||||
// As a list of numbers can contain more than one mode,
|
||||
// the returned result is provided as an array.
|
||||
// The Lua version includes non-numbers.
|
||||
['function ' + Blockly.Lua.FUNCTION_NAME_PLACEHOLDER_ + '(t)',
|
||||
' -- Source: http://lua-users.org/wiki/SimpleStats',
|
||||
' local counts={}',
|
||||
' for _, v in ipairs(t) do',
|
||||
' if counts[v] == nil then',
|
||||
' counts[v] = 1',
|
||||
' else',
|
||||
' counts[v] = counts[v] + 1',
|
||||
' end',
|
||||
' end',
|
||||
' local biggestCount = 0',
|
||||
' for _, v in pairs(counts) do',
|
||||
' if v > biggestCount then',
|
||||
' biggestCount = v',
|
||||
' end',
|
||||
' end',
|
||||
' local temp={}',
|
||||
' for k, v in pairs(counts) do',
|
||||
' if v == biggestCount then',
|
||||
' table.insert(temp, k)',
|
||||
' end',
|
||||
' end',
|
||||
' return temp',
|
||||
'end']);
|
||||
break;
|
||||
|
||||
case 'STD_DEV':
|
||||
functionName = Blockly.Lua.provideFunction_(
|
||||
'math_standard_deviation',
|
||||
['function ' + Blockly.Lua.FUNCTION_NAME_PLACEHOLDER_ + '(t)',
|
||||
' local m',
|
||||
' local vm',
|
||||
' local total = 0',
|
||||
' local count = 0',
|
||||
' local result',
|
||||
' m = #t == 0 and 0 or ' + provideSum() + '(t) / #t',
|
||||
' for _, v in ipairs(t) do',
|
||||
" if type(v) == 'number' then",
|
||||
' vm = v - m',
|
||||
' total = total + (vm * vm)',
|
||||
' count = count + 1',
|
||||
' end',
|
||||
' end',
|
||||
' result = math.sqrt(total / (count-1))',
|
||||
' return result',
|
||||
'end']);
|
||||
break;
|
||||
|
||||
case 'RANDOM':
|
||||
functionName = Blockly.Lua.provideFunction_(
|
||||
'math_random_list',
|
||||
['function ' + Blockly.Lua.FUNCTION_NAME_PLACEHOLDER_ + '(t)',
|
||||
' if #t == 0 then',
|
||||
' return nil',
|
||||
' end',
|
||||
' return t[math.random(#t)]',
|
||||
'end']);
|
||||
break;
|
||||
|
||||
default:
|
||||
throw 'Unknown operator: ' + func;
|
||||
}
|
||||
return [functionName + '(' + list + ')', Blockly.Lua.ORDER_HIGH];
|
||||
};
|
||||
|
||||
Blockly.Lua['math_modulo'] = function(block) {
|
||||
// Remainder computation.
|
||||
var argument0 = Blockly.Lua.valueToCode(block, 'DIVIDEND',
|
||||
Blockly.Lua.ORDER_MULTIPLICATIVE) || '0';
|
||||
var argument1 = Blockly.Lua.valueToCode(block, 'DIVISOR',
|
||||
Blockly.Lua.ORDER_MULTIPLICATIVE) || '0';
|
||||
var code = argument0 + ' % ' + argument1;
|
||||
return [code, Blockly.Lua.ORDER_MULTIPLICATIVE];
|
||||
};
|
||||
|
||||
Blockly.Lua['math_constrain'] = function(block) {
|
||||
// Constrain a number between two limits.
|
||||
var argument0 = Blockly.Lua.valueToCode(block, 'VALUE',
|
||||
Blockly.Lua.ORDER_NONE) || '0';
|
||||
var argument1 = Blockly.Lua.valueToCode(block, 'LOW',
|
||||
Blockly.Lua.ORDER_NONE) || '-math.huge';
|
||||
var argument2 = Blockly.Lua.valueToCode(block, 'HIGH',
|
||||
Blockly.Lua.ORDER_NONE) || 'math.huge';
|
||||
var code = 'math.min(math.max(' + argument0 + ', ' + argument1 + '), ' +
|
||||
argument2 + ')';
|
||||
return [code, Blockly.Lua.ORDER_HIGH];
|
||||
};
|
||||
|
||||
Blockly.Lua['math_random_int'] = function(block) {
|
||||
// Random integer between [X] and [Y].
|
||||
var argument0 = Blockly.Lua.valueToCode(block, 'FROM',
|
||||
Blockly.Lua.ORDER_NONE) || '0';
|
||||
var argument1 = Blockly.Lua.valueToCode(block, 'TO',
|
||||
Blockly.Lua.ORDER_NONE) || '0';
|
||||
var code = 'math.random(' + argument0 + ', ' + argument1 + ')';
|
||||
return [code, Blockly.Lua.ORDER_HIGH];
|
||||
};
|
||||
|
||||
Blockly.Lua['math_random_float'] = function(block) {
|
||||
// Random fraction between 0 and 1.
|
||||
return ['math.random()', Blockly.Lua.ORDER_HIGH];
|
||||
};
|
||||
110
generators/lua/procedures.js
Normal file
110
generators/lua/procedures.js
Normal file
@@ -0,0 +1,110 @@
|
||||
/**
|
||||
* @license
|
||||
* Visual Blocks Language
|
||||
*
|
||||
* Copyright 2016 Google Inc.
|
||||
* https://developers.google.com/blockly/
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
/**
|
||||
* @fileoverview Generating Lua for procedure blocks.
|
||||
* @author rodrigoq@google.com (Rodrigo Queiro)
|
||||
*/
|
||||
'use strict';
|
||||
|
||||
goog.provide('Blockly.Lua.procedures');
|
||||
|
||||
goog.require('Blockly.Lua');
|
||||
|
||||
|
||||
Blockly.Lua['procedures_defreturn'] = function(block) {
|
||||
// Define a procedure with a return value.
|
||||
var funcName = Blockly.Lua.variableDB_.getName(
|
||||
block.getFieldValue('NAME'), Blockly.Procedures.NAME_TYPE);
|
||||
var branch = Blockly.Lua.statementToCode(block, 'STACK');
|
||||
if (Blockly.Lua.STATEMENT_PREFIX) {
|
||||
branch = Blockly.Lua.prefixLines(
|
||||
Blockly.Lua.STATEMENT_PREFIX.replace(/%1/g,
|
||||
'\'' + block.id + '\''), Blockly.Lua.INDENT) + branch;
|
||||
}
|
||||
if (Blockly.Lua.INFINITE_LOOP_TRAP) {
|
||||
branch = Blockly.Lua.INFINITE_LOOP_TRAP.replace(/%1/g,
|
||||
'\'' + block.id + '\'') + branch;
|
||||
}
|
||||
var returnValue = Blockly.Lua.valueToCode(block, 'RETURN',
|
||||
Blockly.Lua.ORDER_NONE) || '';
|
||||
if (returnValue) {
|
||||
returnValue = ' return ' + returnValue + '\n';
|
||||
} else if (!branch) {
|
||||
branch = '';
|
||||
}
|
||||
var args = [];
|
||||
for (var x = 0; x < block.arguments_.length; x++) {
|
||||
args[x] = Blockly.Lua.variableDB_.getName(block.arguments_[x],
|
||||
Blockly.Variables.NAME_TYPE);
|
||||
}
|
||||
var code = 'function ' + funcName + '(' + args.join(', ') + ')\n' +
|
||||
branch + returnValue + 'end\n';
|
||||
code = Blockly.Lua.scrub_(block, code);
|
||||
Blockly.Lua.definitions_[funcName] = code;
|
||||
return null;
|
||||
};
|
||||
|
||||
// Defining a procedure without a return value uses the same generator as
|
||||
// a procedure with a return value.
|
||||
Blockly.Lua['procedures_defnoreturn'] =
|
||||
Blockly.Lua['procedures_defreturn'];
|
||||
|
||||
Blockly.Lua['procedures_callreturn'] = function(block) {
|
||||
// Call a procedure with a return value.
|
||||
var funcName = Blockly.Lua.variableDB_.getName(
|
||||
block.getFieldValue('NAME'), Blockly.Procedures.NAME_TYPE);
|
||||
var args = [];
|
||||
for (var x = 0; x < block.arguments_.length; x++) {
|
||||
args[x] = Blockly.Lua.valueToCode(block, 'ARG' + x,
|
||||
Blockly.Lua.ORDER_NONE) || 'nil';
|
||||
}
|
||||
var code = funcName + '(' + args.join(', ') + ')';
|
||||
return [code, Blockly.Lua.ORDER_HIGH];
|
||||
};
|
||||
|
||||
Blockly.Lua['procedures_callnoreturn'] = function(block) {
|
||||
// Call a procedure with no return value.
|
||||
var funcName = Blockly.Lua.variableDB_.getName(
|
||||
block.getFieldValue('NAME'), Blockly.Procedures.NAME_TYPE);
|
||||
var args = [];
|
||||
for (var x = 0; x < block.arguments_.length; x++) {
|
||||
args[x] = Blockly.Lua.valueToCode(block, 'ARG' + x,
|
||||
Blockly.Lua.ORDER_NONE) || 'nil';
|
||||
}
|
||||
var code = funcName + '(' + args.join(', ') + ')\n';
|
||||
return code;
|
||||
};
|
||||
|
||||
Blockly.Lua['procedures_ifreturn'] = function(block) {
|
||||
// Conditionally return value from a procedure.
|
||||
var condition = Blockly.Lua.valueToCode(block, 'CONDITION',
|
||||
Blockly.Lua.ORDER_NONE) || 'false';
|
||||
var code = 'if ' + condition + ' then\n';
|
||||
if (block.hasReturnValue_) {
|
||||
var value = Blockly.Lua.valueToCode(block, 'VALUE',
|
||||
Blockly.Lua.ORDER_NONE) || 'nil';
|
||||
code += ' return ' + value + '\n';
|
||||
} else {
|
||||
code += ' return\n';
|
||||
}
|
||||
code += 'end\n';
|
||||
return code;
|
||||
};
|
||||
293
generators/lua/text.js
Normal file
293
generators/lua/text.js
Normal file
@@ -0,0 +1,293 @@
|
||||
/**
|
||||
* @license
|
||||
* Visual Blocks Language
|
||||
*
|
||||
* Copyright 2016 Google Inc.
|
||||
* https://developers.google.com/blockly/
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
/**
|
||||
* @fileoverview Generating Lua for text blocks.
|
||||
* @author rodrigoq@google.com (Rodrigo Queiro)
|
||||
*/
|
||||
'use strict';
|
||||
|
||||
goog.provide('Blockly.Lua.texts');
|
||||
|
||||
goog.require('Blockly.Lua');
|
||||
|
||||
|
||||
Blockly.Lua['text'] = function(block) {
|
||||
// Text value.
|
||||
var code = Blockly.Lua.quote_(block.getFieldValue('TEXT'));
|
||||
return [code, Blockly.Lua.ORDER_ATOMIC];
|
||||
};
|
||||
|
||||
Blockly.Lua['text_join'] = function(block) {
|
||||
// Create a string made up of any number of elements of any type.
|
||||
if (block.itemCount_ == 0) {
|
||||
return ['\'\'', Blockly.Lua.ORDER_ATOMIC];
|
||||
} else if (block.itemCount_ == 1) {
|
||||
var argument0 = Blockly.Lua.valueToCode(block, 'ADD0',
|
||||
Blockly.Lua.ORDER_NONE) || '\'\'';
|
||||
var code = argument0;
|
||||
return [code, Blockly.Lua.ORDER_HIGH];
|
||||
} else if (block.itemCount_ == 2) {
|
||||
var argument0 = Blockly.Lua.valueToCode(block, 'ADD0',
|
||||
Blockly.Lua.ORDER_NONE) || '\'\'';
|
||||
var argument1 = Blockly.Lua.valueToCode(block, 'ADD1',
|
||||
Blockly.Lua.ORDER_NONE) || '\'\'';
|
||||
var code = argument0 + ' .. ' + argument1;
|
||||
return [code, Blockly.Lua.ORDER_UNARY];
|
||||
} else {
|
||||
var code = [];
|
||||
for (var n = 0; n < block.itemCount_; n++) {
|
||||
code[n] = Blockly.Lua.valueToCode(block, 'ADD' + n,
|
||||
Blockly.Lua.ORDER_NONE) || '\'\'';
|
||||
}
|
||||
code = 'table.concat({' + code.join(', ') + '})';
|
||||
return [code, Blockly.Lua.ORDER_HIGH];
|
||||
}
|
||||
};
|
||||
|
||||
Blockly.Lua['text_append'] = function(block) {
|
||||
// Append to a variable in place.
|
||||
var varName = Blockly.Lua.variableDB_.getName(
|
||||
block.getFieldValue('VAR'), Blockly.Variables.NAME_TYPE);
|
||||
var argument0 = Blockly.Lua.valueToCode(block, 'TEXT',
|
||||
Blockly.Lua.ORDER_NONE) || '\'\'';
|
||||
return varName + ' = ' + varName + ' .. ' + argument0 + '\n';
|
||||
};
|
||||
|
||||
Blockly.Lua['text_length'] = function(block) {
|
||||
// String or array length.
|
||||
var argument0 = Blockly.Lua.valueToCode(block, 'VALUE',
|
||||
Blockly.Lua.ORDER_HIGH) || '\'\'';
|
||||
return ['#' + argument0, Blockly.Lua.ORDER_HIGH];
|
||||
};
|
||||
|
||||
Blockly.Lua['text_isEmpty'] = function(block) {
|
||||
// Is the string null or array empty?
|
||||
var argument0 = Blockly.Lua.valueToCode(block, 'VALUE',
|
||||
Blockly.Lua.ORDER_HIGH) || '\'\'';
|
||||
return ['#' + argument0 + ' == 0', Blockly.Lua.ORDER_RELATIONAL];
|
||||
};
|
||||
|
||||
Blockly.Lua['text_indexOf'] = function(block) {
|
||||
// Search the text for a substring.
|
||||
var operator = block.getFieldValue('END') == 'FIRST' ?
|
||||
'indexOf' : 'lastIndexOf';
|
||||
var substr = Blockly.Lua.valueToCode(block, 'FIND',
|
||||
Blockly.Lua.ORDER_NONE) || '\'\'';
|
||||
var str = Blockly.Lua.valueToCode(block, 'VALUE',
|
||||
Blockly.Lua.ORDER_NONE) || '\'\'';
|
||||
if (block.getTitleValue('END') == 'FIRST') {
|
||||
var functionName = Blockly.Lua.provideFunction_(
|
||||
'firstIndexOf',
|
||||
['function ' + Blockly.Lua.FUNCTION_NAME_PLACEHOLDER_ +
|
||||
'(str, substr) ',
|
||||
' local i = string.find(str, substr, 1, true)',
|
||||
' if i == nil then',
|
||||
' return 0',
|
||||
' else',
|
||||
' return i',
|
||||
' end',
|
||||
'end']);
|
||||
} else {
|
||||
var functionName = Blockly.Lua.provideFunction_(
|
||||
'lastIndexOf',
|
||||
['function ' + Blockly.Lua.FUNCTION_NAME_PLACEHOLDER_ +
|
||||
'(str, substr)',
|
||||
' local i = string.find(string.reverse(str), ' +
|
||||
'string.reverse(substr), 1, true)',
|
||||
' if i then',
|
||||
' return #str + 2 - i - #substr',
|
||||
' end',
|
||||
' return 0',
|
||||
'end']);
|
||||
}
|
||||
var code = functionName + '(' + str + ', ' + substr + ')';
|
||||
return [code, Blockly.Lua.ORDER_HIGH];
|
||||
};
|
||||
|
||||
Blockly.Lua['text_charAt'] = function(block) {
|
||||
// Get letter at index.
|
||||
// Note: Until January 2013 this block did not have the WHERE input.
|
||||
var where = block.getFieldValue('WHERE') || 'FROM_START';
|
||||
var at = Blockly.Lua.valueToCode(block, 'AT',
|
||||
Blockly.Lua.ORDER_UNARY) || '1';
|
||||
var text = Blockly.Lua.valueToCode(block, 'VALUE',
|
||||
Blockly.Lua.ORDER_NONE) || '\'\'';
|
||||
var code;
|
||||
if (where == 'RANDOM') {
|
||||
var functionName = Blockly.Lua.provideFunction_(
|
||||
'text_random_letter',
|
||||
['function ' + Blockly.Lua.FUNCTION_NAME_PLACEHOLDER_ + '(str)',
|
||||
' local index = math.random(string.len(str))',
|
||||
' return string.sub(str, index, index)',
|
||||
'end']);
|
||||
code = functionName + '(' + text + ')';
|
||||
} else {
|
||||
if (where == 'FIRST') {
|
||||
var start = '1';
|
||||
} else if (where == 'LAST') {
|
||||
var start = '-1';
|
||||
} else {
|
||||
if (where == 'FROM_START') {
|
||||
var start = at;
|
||||
} else if (where == 'FROM_END') {
|
||||
var start = '-' + at;
|
||||
} else {
|
||||
throw 'Unhandled option (text_charAt).';
|
||||
}
|
||||
}
|
||||
if (start.match(/^-?\w*$/)) {
|
||||
code = 'string.sub(' + text + ', ' + start + ', ' + start + ')';
|
||||
} else {
|
||||
// use function to avoid reevaluation
|
||||
var functionName = Blockly.Lua.provideFunction_(
|
||||
'text_char_at',
|
||||
['function ' + Blockly.Lua.FUNCTION_NAME_PLACEHOLDER_ +
|
||||
'(str, index)',
|
||||
' return string.sub(str, index, index)',
|
||||
'end']);
|
||||
code = functionName + '(' + text + ', ' + start + ')';
|
||||
}
|
||||
}
|
||||
return [code, Blockly.Lua.ORDER_HIGH];
|
||||
};
|
||||
|
||||
Blockly.Lua['text_getSubstring'] = function(block) {
|
||||
// Get substring.
|
||||
var text = Blockly.Lua.valueToCode(block, 'STRING',
|
||||
Blockly.Lua.ORDER_NONE) || '\'\'';
|
||||
|
||||
// Get start index.
|
||||
var where1 = block.getFieldValue('WHERE1');
|
||||
var at1 = Blockly.Lua.valueToCode(block, 'AT1',
|
||||
Blockly.Lua.ORDER_UNARY) || '1';
|
||||
if (where1 == 'FIRST') {
|
||||
var start = 1;
|
||||
} else if (where1 == 'FROM_START') {
|
||||
var start = at1;
|
||||
} else if (where1 == 'FROM_END') {
|
||||
var start = '-' + at1;
|
||||
} else {
|
||||
throw 'Unhandled option (text_getSubstring)';
|
||||
}
|
||||
|
||||
// Get end index.
|
||||
var where2 = block.getFieldValue('WHERE2');
|
||||
var at2 = Blockly.Lua.valueToCode(block, 'AT2',
|
||||
Blockly.Lua.ORDER_UNARY) || '1';
|
||||
if (where2 == 'LAST') {
|
||||
var end = -1;
|
||||
} else if (where2 == 'FROM_START') {
|
||||
var end = at2;
|
||||
} else if (where2 == 'FROM_END') {
|
||||
var end = '-' + at2;
|
||||
} else {
|
||||
throw 'Unhandled option (text_getSubstring)';
|
||||
}
|
||||
var code = 'string.sub(' + text + ', ' + start + ', ' + end + ')';
|
||||
return [code, Blockly.Lua.ORDER_HIGH];
|
||||
};
|
||||
|
||||
Blockly.Lua['text_changeCase'] = function(block) {
|
||||
// Change capitalization.
|
||||
var operator = block.getFieldValue('CASE');
|
||||
var argument0 = Blockly.Lua.valueToCode(block, 'TEXT',
|
||||
Blockly.Lua.ORDER_NONE) || '\'\'';
|
||||
if (operator == 'UPPERCASE') {
|
||||
var functionName = 'string.upper';
|
||||
} else if (operator == 'LOWERCASE') {
|
||||
var functionName = 'string.lower';
|
||||
} else if (operator == 'TITLECASE') {
|
||||
var functionName = Blockly.Lua.provideFunction_(
|
||||
'text_titlecase',
|
||||
// There are shorter versions at
|
||||
// http://lua-users.org/wiki/SciteTitleCase
|
||||
// that do not preserve whitespace.
|
||||
['function ' + Blockly.Lua.FUNCTION_NAME_PLACEHOLDER_ + '(str)',
|
||||
' local buf = {}',
|
||||
' local inWord = false',
|
||||
' for i = 1, #str do',
|
||||
' local c = string.sub(str, i, i)',
|
||||
' if inWord then',
|
||||
' table.insert(buf, string.lower(c))',
|
||||
' if string.find(c, "%s") then',
|
||||
' inWord = false',
|
||||
' end',
|
||||
' else',
|
||||
' table.insert(buf, string.upper(c))',
|
||||
' inWord = true',
|
||||
' end',
|
||||
' end',
|
||||
' return table.concat(buf)',
|
||||
'end']);
|
||||
}
|
||||
var code = functionName + '(' + argument0 + ')';
|
||||
return [code, Blockly.Lua.ORDER_HIGH];
|
||||
};
|
||||
|
||||
Blockly.Lua['text_trim'] = function(block) {
|
||||
// Trim spaces.
|
||||
var OPERATORS = {
|
||||
LEFT: '^%s*(,-)',
|
||||
RIGHT: '(.-)%s*$',
|
||||
BOTH: '^%s*(.-)%s*$'
|
||||
};
|
||||
var operator = OPERATORS[block.getFieldValue('MODE')];
|
||||
var text = Blockly.Lua.valueToCode(block, 'TEXT',
|
||||
Blockly.Lua.ORDER_NONE) || '\'\'';
|
||||
var code = 'string.gsub(' + text + ', "' + operator + '", "%1")';
|
||||
return [code, Blockly.Lua.ORDER_HIGH];
|
||||
};
|
||||
|
||||
Blockly.Lua['text_print'] = function(block) {
|
||||
// Print statement.
|
||||
var argument0 = Blockly.Lua.valueToCode(block, 'TEXT',
|
||||
Blockly.Lua.ORDER_NONE) || '\'\'';
|
||||
return 'print(' + argument0 + ')\n';
|
||||
};
|
||||
|
||||
Blockly.Lua['text_prompt_ext'] = function(block) {
|
||||
// Prompt function.
|
||||
if (block.getField('TEXT')) {
|
||||
// Internal message.
|
||||
var msg = Blockly.Lua.quote_(block.getFieldValue('TEXT'));
|
||||
} else {
|
||||
// External message.
|
||||
var msg = Blockly.Lua.valueToCode(block, 'TEXT',
|
||||
Blockly.Lua.ORDER_NONE) || '\'\'';
|
||||
}
|
||||
|
||||
var functionName = Blockly.Lua.provideFunction_(
|
||||
'text_prompt',
|
||||
['function ' + Blockly.Lua.FUNCTION_NAME_PLACEHOLDER_ + '(msg)',
|
||||
' io.write(msg)',
|
||||
' io.flush()',
|
||||
' return io.read()',
|
||||
'end']);
|
||||
var code = functionName + '(' + msg + ')';
|
||||
|
||||
var toNumber = block.getFieldValue('TYPE') == 'NUMBER';
|
||||
if (toNumber) {
|
||||
code = 'tonumber(' + code + ', 10)';
|
||||
}
|
||||
return [code, Blockly.Lua.ORDER_HIGH];
|
||||
};
|
||||
|
||||
Blockly.Lua['text_prompt'] = Blockly.Lua['text_prompt_ext'];
|
||||
46
generators/lua/variables.js
Normal file
46
generators/lua/variables.js
Normal file
@@ -0,0 +1,46 @@
|
||||
/**
|
||||
* @license
|
||||
* Visual Blocks Language
|
||||
*
|
||||
* Copyright 2016 Google Inc.
|
||||
* https://developers.google.com/blockly/
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
/**
|
||||
* @fileoverview Generating Lua for variable blocks.
|
||||
* @author rodrigoq@google.com (Rodrigo Queiro)
|
||||
*/
|
||||
'use strict';
|
||||
|
||||
goog.provide('Blockly.Lua.variables');
|
||||
|
||||
goog.require('Blockly.Lua');
|
||||
|
||||
|
||||
Blockly.Lua['variables_get'] = function(block) {
|
||||
// Variable getter.
|
||||
var code = Blockly.Lua.variableDB_.getName(block.getFieldValue('VAR'),
|
||||
Blockly.Variables.NAME_TYPE);
|
||||
return [code, Blockly.Lua.ORDER_ATOMIC];
|
||||
};
|
||||
|
||||
Blockly.Lua['variables_set'] = function(block) {
|
||||
// Variable setter.
|
||||
var argument0 = Blockly.Lua.valueToCode(block, 'VALUE',
|
||||
Blockly.Lua.ORDER_NONE) || '0';
|
||||
var varName = Blockly.Lua.variableDB_.getName(
|
||||
block.getFieldValue('VAR'), Blockly.Variables.NAME_TYPE);
|
||||
return varName + ' = ' + argument0 + '\n';
|
||||
};
|
||||
74
lua_compressed.js
Normal file
74
lua_compressed.js
Normal file
File diff suppressed because one or more lines are too long
@@ -49,6 +49,18 @@
|
||||
<script src="../../generators/dart/variables.js"></script>
|
||||
<script src="../../generators/dart/procedures.js"></script>
|
||||
|
||||
<script src="../../generators/lua.js"></script>
|
||||
<script src="unittest_lua.js"></script>
|
||||
<script src="../../generators/lua/logic.js"></script>
|
||||
<script src="../../generators/lua/loops.js"></script>
|
||||
<script src="../../generators/lua/math.js"></script>
|
||||
<script src="../../generators/lua/text.js"></script>
|
||||
<script src="../../generators/lua/lists.js"></script>
|
||||
<script src="../../generators/lua/colour.js"></script>
|
||||
<script src="../../generators/lua/variables.js"></script>
|
||||
<script src="../../generators/lua/procedures.js"></script>
|
||||
|
||||
|
||||
<script src="unittest.js"></script>
|
||||
<script src="../../msg/messages.js"></script>
|
||||
<script src="../../blocks/logic.js"></script>
|
||||
@@ -153,6 +165,11 @@ function toDart() {
|
||||
var code = Blockly.Dart.workspaceToCode(workspace);
|
||||
setOutput(code);
|
||||
}
|
||||
|
||||
function toLua() {
|
||||
var code = Blockly.Lua.workspaceToCode(workspace);
|
||||
setOutput(code);
|
||||
}
|
||||
</script>
|
||||
|
||||
<style>
|
||||
@@ -287,6 +304,7 @@ h1 {
|
||||
<input type="button" value="Python" onclick="toPython()">
|
||||
<input type="button" value="PHP" onclick="toPhp()">
|
||||
<input type="button" value="Dart" onclick="toDart()">
|
||||
<input type="button" value="Lua" onclick="toLua()">
|
||||
</p>
|
||||
</td></tr><tr><td height="99%">
|
||||
<textarea id="importExport" readonly="readonly" wrap="off"></textarea>
|
||||
|
||||
163
tests/generators/unittest_lua.js
Normal file
163
tests/generators/unittest_lua.js
Normal file
@@ -0,0 +1,163 @@
|
||||
/**
|
||||
* @license
|
||||
* Visual Blocks Language
|
||||
*
|
||||
* Copyright 2016 Google Inc.
|
||||
* https://developers.google.com/blockly/
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
/**
|
||||
* @fileoverview Generating Lua for unit test blocks.
|
||||
* @author rodrigoq@google.com (Rodrigo Queiro)
|
||||
*/
|
||||
'use strict';
|
||||
|
||||
Blockly.Lua['unittest_main'] = function(block) {
|
||||
// Container for unit tests.
|
||||
var resultsVar = Blockly.Lua.variableDB_.getName('unittestResults',
|
||||
Blockly.Variables.NAME_TYPE);
|
||||
var functionName = Blockly.Lua.provideFunction_(
|
||||
'unittest_report',
|
||||
['function ' + Blockly.Lua.FUNCTION_NAME_PLACEHOLDER_ + '()',
|
||||
' -- Create test report.',
|
||||
' local report = {}',
|
||||
' local summary = {}',
|
||||
' local fails = 0',
|
||||
' for _, v in pairs(' + resultsVar + ') do',
|
||||
' if v["success"] then',
|
||||
' table.insert(summary, ".")',
|
||||
' else',
|
||||
' table.insert(summary, "F")',
|
||||
' fails = fails + 1',
|
||||
' table.insert(report, "FAIL: " .. v["title"])',
|
||||
' table.insert(report, v["log"])',
|
||||
' end',
|
||||
' end',
|
||||
' table.insert(report, 1, table.concat(summary))',
|
||||
' table.insert(report, "")',
|
||||
' table.insert(report, "Number of tests run: " .. #' + resultsVar + ')',
|
||||
' table.insert(report, "")',
|
||||
' if fails > 0 then',
|
||||
' table.insert(report, "FAILED (failures=" .. fails .. ")")',
|
||||
' else',
|
||||
' table.insert(report, "OK")',
|
||||
' end',
|
||||
' return table.concat(report, "\\n")',
|
||||
'end']);
|
||||
// Setup global to hold test results.
|
||||
var code = resultsVar + ' = {}\n';
|
||||
// Run tests (unindented).
|
||||
code += Blockly.Lua.statementToCode(block, 'DO')
|
||||
.replace(/^ /, '').replace(/\n /g, '\n');
|
||||
var reportVar = Blockly.Lua.variableDB_.getDistinctName(
|
||||
'report', Blockly.Variables.NAME_TYPE);
|
||||
code += reportVar + ' = ' + functionName + '()\n';
|
||||
// Destroy results.
|
||||
code += resultsVar + ' = nil\n';
|
||||
// Print the report.
|
||||
code += 'print(' + reportVar + ')\n';
|
||||
return code;
|
||||
};
|
||||
|
||||
Blockly.Lua['unittest_main'].defineAssert_ = function(block) {
|
||||
var resultsVar = Blockly.Lua.variableDB_.getName('unittestResults',
|
||||
Blockly.Variables.NAME_TYPE);
|
||||
var functionName = Blockly.Lua.provideFunction_(
|
||||
'assertEquals',
|
||||
['function ' + Blockly.Lua.FUNCTION_NAME_PLACEHOLDER_ +
|
||||
'(actual, expected, message)',
|
||||
' -- Asserts that a value equals another value.',
|
||||
' assert(' + resultsVar + ' ~= nil, ' +
|
||||
'"Orphaned assert equals: " .. message)',
|
||||
' if type(actual) == "table" and type(expected) == "table" then',
|
||||
' local lists_match = #actual == #expected',
|
||||
' if lists_match then',
|
||||
' for i, v1 in ipairs(actual) do',
|
||||
' local v2 = expected[i]',
|
||||
' if type(v1) == "number" and type(v2) == "number" then',
|
||||
' if math.abs(v1 - v2) > 1e-9 then',
|
||||
' lists_match = false',
|
||||
' end',
|
||||
' elseif v1 ~= v2 then',
|
||||
' lists_match = false',
|
||||
' end',
|
||||
' end',
|
||||
' end',
|
||||
' if lists_match then',
|
||||
' table.insert(' + resultsVar +
|
||||
', {success=true, log="OK", title=message})',
|
||||
' return',
|
||||
' else',
|
||||
' -- produce the non-matching strings for a human-readable error',
|
||||
' expected = "{" .. table.concat(expected, ", ") .. "}"',
|
||||
' actual = "{" .. table.concat(actual, ", ") .. "}"',
|
||||
' end',
|
||||
' end',
|
||||
' if actual == expected then',
|
||||
' table.insert(' + resultsVar +
|
||||
', {success=true, log="OK", title=message})',
|
||||
' else',
|
||||
' table.insert(' + resultsVar + ', {success=false, ' +
|
||||
'log=string.format("Expected: %s\\nActual: %s"' +
|
||||
', expected, actual), title=message})',
|
||||
' end',
|
||||
'end']);
|
||||
return functionName;
|
||||
};
|
||||
|
||||
Blockly.Lua['unittest_assertequals'] = function(block) {
|
||||
// Asserts that a value equals another value.
|
||||
var message = Blockly.Lua.quote_(block.getFieldValue('MESSAGE'));
|
||||
var actual = Blockly.Lua.valueToCode(block, 'ACTUAL',
|
||||
Blockly.Lua.ORDER_NONE) || 'nil';
|
||||
var expected = Blockly.Lua.valueToCode(block, 'EXPECTED',
|
||||
Blockly.Lua.ORDER_NONE) || 'nil';
|
||||
return Blockly.Lua['unittest_main'].defineAssert_() +
|
||||
'(' + actual + ', ' + expected + ', ' + message + ')\n';
|
||||
};
|
||||
|
||||
Blockly.Lua['unittest_assertvalue'] = function(block) {
|
||||
// Asserts that a value is true, false, or null.
|
||||
var message = Blockly.Lua.quote_(block.getFieldValue('MESSAGE'));
|
||||
var actual = Blockly.Lua.valueToCode(block, 'ACTUAL',
|
||||
Blockly.Lua.ORDER_NONE) || 'nil';
|
||||
var expected = block.getFieldValue('EXPECTED');
|
||||
if (expected == 'TRUE') {
|
||||
expected = 'true';
|
||||
} else if (expected == 'FALSE') {
|
||||
expected = 'false';
|
||||
} else if (expected == 'NULL') {
|
||||
expected = 'nil';
|
||||
}
|
||||
return Blockly.Lua.unittest_main.defineAssert_() +
|
||||
'(' + actual + ', ' + expected + ', ' + message + ')\n';
|
||||
};
|
||||
|
||||
Blockly.Lua['unittest_fail'] = function(block) {
|
||||
// Always assert an error.
|
||||
var resultsVar = Blockly.Lua.variableDB_.getName('unittestResults',
|
||||
Blockly.Variables.NAME_TYPE);
|
||||
var message = Blockly.Lua.quote_(block.getFieldValue('MESSAGE'));
|
||||
var functionName = Blockly.Lua.provideFunction_(
|
||||
'unittest_fail',
|
||||
['function ' + Blockly.Lua.FUNCTION_NAME_PLACEHOLDER_ + '(message)',
|
||||
' -- Always assert an error.',
|
||||
' assert(' + resultsVar +
|
||||
' ~= nil, "Orphaned assert fail: " .. message)',
|
||||
' table.insert(' + resultsVar +
|
||||
', {success=false, log="Fail.", title=message})',
|
||||
'end']);
|
||||
return functionName + '(' + message + ')\n';
|
||||
};
|
||||
@@ -40,6 +40,15 @@
|
||||
<script src="../generators/dart/colour.js"></script>
|
||||
<script src="../generators/dart/variables.js"></script>
|
||||
<script src="../generators/dart/procedures.js"></script>
|
||||
<script src="../generators/lua.js"></script>
|
||||
<script src="../generators/lua/logic.js"></script>
|
||||
<script src="../generators/lua/loops.js"></script>
|
||||
<script src="../generators/lua/math.js"></script>
|
||||
<script src="../generators/lua/text.js"></script>
|
||||
<script src="../generators/lua/lists.js"></script>
|
||||
<script src="../generators/lua/colour.js"></script>
|
||||
<script src="../generators/lua/variables.js"></script>
|
||||
<script src="../generators/lua/procedures.js"></script>
|
||||
<script src="../msg/messages.js"></script>
|
||||
<script src="../blocks/logic.js"></script>
|
||||
<script src="../blocks/loops.js"></script>
|
||||
@@ -571,6 +580,8 @@ h1 {
|
||||
<input type="button" value="To PHP" onclick="toCode('PHP')">
|
||||
|
||||
<input type="button" value="To Dart" onclick="toCode('Dart')">
|
||||
|
||||
<input type="button" value="To Lua" onclick="toCode('Lua')">
|
||||
<br>
|
||||
<textarea id="importExport" style="width: 26%; height: 12em"
|
||||
onchange="taChange();" onkeyup="taChange()"></textarea>
|
||||
|
||||
Reference in New Issue
Block a user