Defining and Calling Functions

As programs grow, the same few lines often appear in many places. A function solves this. You give a block of code a name once, and then you run it by that name whenever you need it.

function printDivider()
    print("----------")
end

print("Order #1")
printDivider()
print("Order #2")
printDivider()

Output:

Order #1
----------
Order #2
----------

The function ... end block is a definition. It creates the function and gives it the name printDivider, but it does not run the code inside yet.

The line printDivider() is a call. Lua jumps into the function, runs its body, and then comes back to the line after the call. There are two calls here, so you see two dividers.

The parentheses make it a call. printDivider is only the name; printDivider() runs it. You have been calling functions since the first lesson, because print, io.write and io.read are functions too. Now you are writing your own.

Define first, call after

Lua runs a file from top to bottom, and a function exists only after its definition has run. If you call it above the definition, the name is still empty (nil):

print("Start")
printDivider()

function printDivider()
    print("----------")
end

Output:

Start
/usr/bin/lua5.4: main.lua:2: attempt to call a nil value (global 'printDivider')

"attempt to call a nil value" almost always means one of two things. Either the function is called before it is defined, or its name is misspelled.

The message also says global. A function defined with plain function is a global name, like a variable without local. You can write local function printDivider() to keep the name local. The short programs in this course use plain function, which is fine for small scripts.

Why use functions?

If you want a different divider later, you change one function body, and every call uses the new version. A good name also makes code easier to read: printDivider() tells you what happens without reading the body.

In the exercise, define a function named greet, and a loop will call it as many times as the input says.