Lesson 5 of 10

Functions and multiple return values

Goal

Returning several values with return and defaults with or

01

Explanation

You define a function with function name(a, b) ... end, and it's best to put local before it, just as you do with variables. A function hands back its result with return, and in Lua you can return more than one value, as in return newHp, healed. The caller receives them like this: local hp, healed = heal(90), with no table or object needed to bundle them.

Lua doesn't let you write default values in the line that defines the function. An argument that wasn't passed arrives as nil, so you write amount = amount or 25 at the top of the function. This is safe with zero, because zero counts as true in Lua.

But this approach fails with booleans: loud = loud or true always sets loud to true, even when the caller passes false explicitly, so for those you write if loud == nil then loud = true end. And remember that local hp = heal(90) takes only the first value and drops the rest without any error.

02

Your task

Write the function heal(hp, amount, maxHp), with amount defaulting to 25 and maxHp defaulting to 100. It returns two values: the health after healing, without going over maxHp, and then the amount actually healed.

Checks

5 checks
  1. heal is defined
  2. Returns two values: the new health, then the amount
  3. Health doesn't go over maxHp, and the amount is what was actually healed
  4. amount defaults to 25
  5. maxHp defaults to 100
main.lua
OutputLua 5.4 (wasmoon)

Loading Lua.

–/5

Checks start once the environment is ready.

5 checks listed under “Your task”.