Back

Debug Challenge: Tables

divider

Objective

Four programs that use tables, each with exactly one thing wrong. Two of them crash and two of them do not, and the two that do not are the interesting ones.

Every one of these is a mistake the exam reference sheet would treat differently from Lua. That is not a coincidence.


The Four Programs


Bug 1

Three names in the table. This prints nil, then two of them.

Bug 1
local crew = {"Ada", "Bo", "Cy"}
for i = 0, #crew - 1 do
print(crew[i])
end

Bug 2

This should make a copy before changing anything. It prints The original still starts with 999.

Bug 2
local original = {10, 20, 30}
local backup = original
backup[1] = 999
print("The original still starts with " .. original[1])

There is no one-line fix for this one, and saying so is part of the answer.


Bug 3

Three scores in the table. This prints all three and then nil.

Bug 3
local scores = {5, 10, 15}
for i = 1, #scores + 1 do
print(scores[i])
end

Say what the exam reference sheet would do here instead, and which of the two behaviors you would rather have.


Bug 4

Four circles expected. It stops with bad argument #3 to 'circle' (number expected, got nil).

Bug 4
local xs = {120, 260, 400, 540}
local ys = {180, 320, 240}
function love.draw()
for i, x in ipairs(xs) do
love.graphics.circle("fill", x, ys[i], 30)
end
end

Submit

For each program, give:

  • One sentence on what was wrong
  • The corrected line of code, or a description if one line will not do it
  • For bugs 2 and 3: what the exam reference sheet would do instead

Bug 4 has two correct answers. Give both, and say what each one draws.

Worth 5 points, graded on completion.

Commence Debugging