Feel free to run the following chunks in the interpreter, but it is better if you try to guess first what the output will be, from what you have learned in class.
1. What is the output of the following chunk, and why?
Answers:
Because only nil
and false
are false in Lua, everything else is true.
2. What is the output of the following chunk, and why?
Answer:
First a
is a number, then we assign the value of the print
function to it,
which is a function. Then we call a
, which actually calls the print
function.
3. What is the output of the following chunk, and why?
Answer:
In the first print
the variable i
does not exist, so its value is nil
,
then f
assigns to 10
to the global variable i
, and this is what the second
print
prints. Function g
assigns 5
to a local variable i
that is shadowing
the global i
, so the global i
is unaffected, and the last print
still prints 10
.
4. Write a chunk that counts odd numbers backwards from 99 to 1 (99, 97, 95, …, 5, 3, 1), printing each number and them printing their sum. Do it in three ways: with a while loop, with a repeat loop, and using the numeric for.
Answers:
5. Write a function quadratic(a, b, c)
that returns the two solutions
of the quadratic equation with coeficients a
, b
, and c
. Use
the quadratic formula.
You can take the square root of a number in Lua with the math.sqrt
function.
Do not worry about the case where the input to the square root is negative.