Back

Activity 1.22: Handing an Answer Back

divider

Activity 1.22

Handing an Answer Back

Key Concepts

Functions That Answer

Where a Name Lives

Two Answers at Once

Yesterday's Functions Did Something

local function shout(text)
print(text .. "!")
end
shout("hi")

Yesterday's Functions Did Something

local function shout(text)
print(text .. "!")
end
shout("hi")

Draw a tree, print a line. You call it for the effect.

Today's Answer Something

local function double(n)
return n * 2
end
print(double(21))

Today's Answer Something

local function double(n)
return n * 2
end
print(double(21))
Terminal window
42

double(21) becomes 42. The call turns into a value, right where it was written.

You Have Used These All Year

tonumber("16")
Hands back 16.
math.random(1, 20)
Hands back a number.
love.mouse.getPosition()
Hands back two.
love.keyboard.isDown("left")
Hands back a boolean.

Today you write your own.

No return Means nil

local function shout(text)
print(text .. "!")
end
local result = shout("hi")
print("result is " .. tostring(result))

No return Means nil

local function shout(text)
print(text .. "!")
end
local result = shout("hi")
print("result is " .. tostring(result))
Terminal window
hi!
result is nil

It printed, and it handed back nothing. Printing and returning are different jobs.

The most common mix-up in this session, by a distance.

return Also Stops the Function

The moment return runs, the function is over. Anything below it in that branch never happens.

Which is useful, and which is also how people accidentally delete half a function.

Names Made Inside Stay Inside

local function makeIt()
local hidden = 99
return hidden
end
print(makeIt())
print("outside: " .. tostring(hidden))

Names Made Inside Stay Inside

local function makeIt()
local hidden = 99
return hidden
end
print(makeIt())
print("outside: " .. tostring(hidden))
Terminal window
99
outside: nil

That is scope, and you met it at session 16 when i vanished after its loop.

Scope Is a Feature

Two functions can both use a variable called total and never collide.

Without it, every name in a large program would have to be different from every other name in it.

Which Leads Somewhere Strange

local score = 10
local function bump(score)
score = score + 5
return score
end
print(bump(score), score)

Which Leads Somewhere Strange

local score = 10
local function bump(score)
score = score + 5
return score
end
print(bump(score), score)
Terminal window
15 10

The function returned 15 and the outside score is still 10.

The parameter is its own name. Same spelling, different variable.

And You Can Hand Back Two

local function minMax(a, b)
if a < b then
return a, b
else
return b, a
end
end
local lo, hi = minMax(9, 4)
print(lo, hi)

And You Can Hand Back Two

local function minMax(a, b)
if a < b then
return a, b
else
return b, a
end
end
local lo, hi = minMax(9, 4)
print(lo, hi)
Terminal window
4 9

Which is exactly what love.mouse.getPosition() has been doing since session 13.

Today's Objectives

  • Write a function that returns a value
  • Use a returned value in an expression
  • Say why a name made inside a function is not visible outside
  • Return two values at once

Key Terms

return
Hands a value back and ends the function immediately.
Return value
What the call turns into.
Scope
Where a name exists. A local made inside a function exists only inside it.
Shadowing
An inner name hiding an outer one that is spelled the same.

'F' → Fullscreen

divider

Build

Terminal today. Copy template-console.

Task 1: Two Functions, Two Jobs

Copy template-console to 1-22-return and write both:

main.lua
local function shout(text)
print(text .. "!")
end
local result = shout("hi")
print("result is " .. tostring(result))
Terminal
hi!
result is nil

Then write double from the slides and store its answer in a variable. Write down what each of the two functions gave back.

Task 2: Use the Answer

main.lua
local function area(w, h)
return w * h
end
local kitchen = area(3, 4)
local hall = area(2, 6)
print(kitchen + hall)
Terminal
24

The two calls became numbers and then got added together. Now call area inside another call — try print(area(area(2, 3), 4)) and work out the answer before you run it.

Task 3: Write Three of Your Own

Each one takes something and hands something back:

  • celsius(f) — turns Fahrenheit into Celsius
  • isEven(n) — hands back true or false
  • biggest(a, b, c) — hands back the largest of three

isEven can be written with an if, and it can also be written in one line with no if at all. Find the second way if you can.

Task 4: Scope

Run both of these and record the output:

main.lua
local function makeIt()
local hidden = 99
return hidden
end
print(makeIt())
print("outside: " .. tostring(hidden))
main.lua
local score = 10
local function bump(score)
score = score + 5
return score
end
print(bump(score), score)

The second one is the surprising one. The function changed score and the outer score did not move. Write down both numbers and explain them to the person next to you before you read on.

Task 5: Break It on Purpose (Required)

Write a function that computes something and forgets to return it:

main.lua
local function noReturn(n)
n * 2
end
Terminal
Error: Syntax error: main.lua:2: '=' expected near '*'

This one will not even start. Lua reads n * 2 on its own and expects it to be the left side of an assignment. Copy the message down.

Then make the forgetful version that does run: put local answer = n * 2 in the function with no return, and use it. That one has no error at all, and it is the version you will actually write by accident.

Challenge (Optional): Two Answers

Write minMax(a, b) from the slides, then write stats(t) that takes a table of numbers and hands back three things: the total, the count, and the average.

It is a traversal from session 20 with a return at the end.

divider

Same Idea, Exam Notation

The exam's procedures return values too, and the capture is written with the arrow you already know.

Lua
local function area(w, h)
return w * h
end
local kitchen = area(3, 4)
Exam Notation
PROCEDURE area(w, h)
{
RETURN(w * h)
}
kitchen ← area(3, 4)
LuaExam notation
Hand a value backreturn w * hRETURN(w * h)
Catch itlocal kitchen = area(3, 4)kitchen ← area(3, 4)

RETURN takes parentheses and Lua's return does not. It also behaves the same way in both: it can appear anywhere, and it ends the procedure immediately.

The exam has one word for both kinds. A procedure that returns a value and one that does not are both PROCEDURE. Lua is the same — function either way — so the difference is entirely in whether the body says return.
divider

Checkpoint

  • You recorded what a function with no return hands back
  • Two calls to area were added together
  • All three of your own functions return values
  • Both scope results are written down, including the two numbers from the shadowing one
  • Both versions of the forgotten return were run
divider

Reflection

Answer the following questions before submitting your work.

  1. A function that prints and a function that returns look similar and are not. Explain the difference, and describe what goes wrong if you try to use the answer from the printing one.
  2. bump(score) returned 15 and the outer score stayed 10. Explain why, and say what you would have to write to actually change the outer one.
  3. One forgotten return gave a syntax error and the other gave no error at all. Explain the difference between the two versions, and say which one you would rather write by mistake.
divider

Submit

Submit the required files to the appropriate dropbox.

Activity Complete