Back

Debug Challenge: Functions

divider

Objective

Four programs with functions in them, each with exactly one thing wrong. Two crash, two do not, and in three of the four the error message names a line that is not where the mistake is.

That gap — between where a program notices and where it went wrong — is most of what makes debugging a skill rather than a lookup.


The Four Programs


Bug 1

This prints 10 and then stops with an error about arithmetic on a nil value.

Bug 1
local function double(n)
print(n * 2)
end
local answer = double(5)
print("Answer plus one: " .. answer + 1)

Bug 2

The player loses a life. It prints Lives left: 3.

Bug 2
local lives = 3
local function loseALife(lives)
lives = lives - 1
return lives
end
loseALife(lives)
print("Lives left: " .. lives)

The function is correct. Something around it is not.


Bug 3

This should add up the table and print Total: 20. It prints Total: 4.

Bug 3
local function total(t)
local sum = 0
for i, v in ipairs(t) do
sum = sum + v
return sum
end
end
print("Total: " .. total({4, 6, 10}))

Bug 4

This stops immediately with attempt to call global 'greet' (a nil value).

Bug 4
print(greet("Ada"))
local function greet(name)
return "Hello " .. name
end

Submit

For each program, give:

  • One sentence on what was wrong
  • The corrected line of code
  • Which line the error names, and which line the mistake is on — for the two that produce errors

Bug 2 is the one to spend time on. There is nothing wrong inside the function, and writing down exactly what happened to the value is worth more than the fix.

Worth 5 points, graded on completion.

Commence Debugging