Added function to create a string from a table

This commit is contained in:
2021-06-30 17:46:07 -04:00
parent e5f9a26dc6
commit 41d591a69b
2 changed files with 65 additions and 0 deletions

View File

@@ -406,3 +406,16 @@ function toBin(num)
end
return binNum;
end
--Print a table
function printTable(ary)
local tableString = "[";
for cnt = 1, #ary do
tableString = tableString .. tostring(ary[cnt]);
if(cnt < #ary) then
tableString = tableString .. ", ";
end
end
tableString = tableString .. "]";
return tableString;
end

View File

@@ -488,6 +488,52 @@ local function testToBin()
end
end
local function testPrintTable()
local failed = false; --Signals whether a test was failed
--Test 1
local nums = {};
local correctAnswer = "[]";
local answer = printTable(nums);
if(answer ~= correctAnswer) then
io.write("printTable int failed the first test\n");
end
--Test 2
nums = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
correctAnswer = "[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]";
answer = printTable(nums);
if(answer ~= correctAnswer) then
io.write("printTable int failed the second test\n");
end
--Test 3
nums = {-3, -2, -1, 0, 1, 2, 3};
correctAnswer = "[-3, -2, -1, 0, 1, 2, 3]";
answer = printTable(nums);
if(answer ~= correctAnswer) then
io.write("printTable int failed the third test\n");
end
--Test 4
local strings = {"A", "B", "C"};
correctAnswer = "[A, B, C]";
answer = printTable(strings);
if(answer ~= correctAnswer) then
io.write("printTable string failed the first test\n");
end
--Test 5
strings = {"abc", "def", "ghi"};
correctAnswer = "[abc, def, ghi]";
answer = printTable(strings);
if(answer ~= correctAnswer) then
io.write("printTable string failed the second test\n");
end
--Print a message if all of the tests passed
if(not failed) then
io.write("printTable passed all tests\n");
end
end
--Create the timer to time each test
local timer = Stopwatch:create();
@@ -581,3 +627,9 @@ timer:start();
testToBin();
timer:stop();
io.write("It took " .. timer:getString() .. " to run this test\n");
--Test printTable
timer:start();
testPrintTable();
timer:stop();
io.write("It took " .. timer:getString() .. " to run this test\n");