Copyright by Kurt Jung, Aaron Brown

Safari, the world’s most comprehensive technology and business learning platform.

Find the exact information you need to solve a problem on the fly, or go deeper to master the technologies and skills you need to succeed

Start Free Trial

No credit card required

O'Reilly logo

Appendix A. Answers

Exercise 1 Solution

Because the "p" in print needs to be lowercase.

Exercise 2 Solution

"ABC123"

Exercise 3 Solution

Because it reduces to the following, and the attempt to concatenate a Boolean value will trigger an error:

false .. 123

Exercise 4 Solution

One (the first one). More than one branch of an if is never executed. The first branch when a true test expression is executed, and after that, the if is exited.

Exercise 5 Solution

for N = 10, 2, −2 do
  print(N)
end

Exercise 1 Solution

function TypedToString(Val)
  return type(Val) .. ": " .. tostring(Val)
end

Exercise 2 Solution

function SumProd(A, B)
  return A + B, A * B
end

Exercise 3 Solution

It will print the following:

6       10      25

(SumProd(3, 3) returns 6, 9, which is adjusted to one value. SumProd(5, 5) returns 10, 25, and both values are used.

Exercise 4 Solution

It prints North America. (The Continent inside F is local—assigning to it has no effect on the global Continent.)

Exercise 5 Solution

For the functions returned to be closures (and thus have private state), Dots needs to be local. Because it's global, all the functions returned share the same state, so they all do the same thing. The fix is simply this:

function MakeDotter(N)
  local Dots = ""
  for I = 1, N do
    Dots = Dots .. "."
  end
  return function(Str)
    return Str .. Dots
  end
end

As mentioned earlier, forgetting to make a variable local is a common source of bugs.

Exercise 1 Solution

C

To figure this sort of thing out, work from left to right: figure ...

Find the exact information you need to solve a problem on the fly, or go deeper to master the technologies and skills you need to succeed

Start Free Trial

No credit card required