Consider the following program that prints out a list of student names and their grades.
local student_grades = {
Alice = { 95, 87, 72 },
Bob = { 67, 54, 72 }
}
for name, grades in pairs(student_grades) do
io.write(name .. ":\n")
for _, grade in ipairs(grades) do
io.write("\t" .. grade .. "\n")
end
end
What happens if we need to record the details of a new student and want to print out the list again? We need to repeat all the code in the for loop, ending up with a program like this one.
local student_grades = {
Alice = { 95, 87, 72 },
Bob = { 67, 54, 72 }
}
for name, grades in pairs(student_grades) do
io.write(name .. ":\n")
for _, grade in ipairs(grades) do
io.write("\t" .. grade .. "\n")
end
end
student_grades["Carol"] = { 42, 57, 38 }
for name, grades in pairs(student_grades) do
io.write(name .. ":\n")
for _, grade in ipairs(grades) do
io.write("\t" .. grade .. "\n")
end
end
It would be nice if we could avoid such repetition. It turns out we can do just
that with something called a function. Take a look at this next program. We
define a function called show_grades, that contains the statements necessary to
print out the grades for each student. Similar to how we can assign a label to
a value with variables, we can assign a label to some code with a function.
-- Functions.
local student_grades = {
Alice = { 95, 87, 72 },
Bob = { 67, 54, 72 }
}
local function show_grades(student_grades)
-- Function to print out a list of grades for each student.
for name, grades in pairs(student_grades) do
io.write(name .. ":\n")
for _, grade in ipairs(grades) do
io.write("\t" .. grade .. "\n")
end
end
end
show_grades(student_grades)
student_grades["Carol"] = { 42, 57, 38 }
show_grades(student_grades)Function definitions start with the function keyword. Like variables they are
global by default. As with variables, making functions global can cause issues in
large programs; so we prefix it with the local keyword as we do for variables.
The next part of the function is a list of arguments enclosed in parenthesis
(). These arguments will be the variables we pass into the function for it to
operate on. In our example we passed in a single argument called student_grades.
The first line of a function is often a comment that briefly outlines the functions purpose. This is optional but good practice. Next come the lines of code that make up the functions action. These lines of code are run whenever we call the function from somewhere else in our code.
Finally, a function ends with the end keyword. Much like a loop or conditional
statement does.
Functions can be given any name you like as long as they adhere to a few basic rules.
for or local).Valid names are do_stuff, myFunction, CopyProcess2. Invalid names are
2multiplier, long name with spaces.
Typically we use only lowercase letters in function names, and an underscore _
where we would like a space to be.
The arguments are the variables we want to pass into our function. We give the names
of the arguments in parenthesis (). They are available to the code that makes
up the function as local variables.
When we pass a variable to a function Lua uses pass by value. That is, a copy of the value in the variable is made and assigned to the argument. Consider the following program and its output.
-- Pass by value.
local num = 10
local function add2(num)
io.write("Adding 2 to " .. num .. ".\n")
num = num + 2
io.write("Num is " .. num .. " inside the function.\n")
end
io.write("Num is " .. num .. " before calling the function.\n")
add2(num)
io.write("Num is " .. num .. " after calling the function.\n")Num is 10 before calling the function.
Adding 2 to 10.
Num is 12 inside the function.
Num is 10 after calling the function.
So what's going on here? The value in num - 10 - is passed to the function by
making a copy. The function has it's own variable called num which it increases
by 2. When the function ends, this value (the copy) goes away. We are left with
the original num which is still 10.
Tables are the exception to the rule on passing variables by value. They are pass by reference. This means a copy of the table isn't made (as this could be very large, and copying it would be too slow), so the original table makes its way into the function. This means you can modify, add, and remove keys and values in a table inside the function, and when the function ends the changes will be visible to the calling code.
Consider the following program.
-- Pass by reference.
local students = { "Alice", "Bob", "Carol" }
local function edit_table(students)
-- Add, edit, and remove students.
table.insert(students, "Dave")
table.remove(students, 2)
students[1] = "Eve"
end
io.write(table.concat(students, ", ") .. "\n")
edit_table(students)
io.write(table.concat(students, ", ") .. "\n")
The output of this program shows the changes are in effect after the function has finished running.
Alice, Bob, Carol
Eve, Carol, Dave
One thing you cannot do in a function is to reassign the variable students to
a new table value. If you do, the change is not reflected in the calling code.
local grades = { 97, 43, 56, 72 }
local function reassign_grades(grades)
grades = { 10, 32, 9, 70 }
end
io.write(table.concat(grades, ", ") .. "\n")
reassign_grades(grades)
io.write(table.concat(grades, ", ") .. "\n")
This outputs the original table after running the function.
97, 43, 56, 72
97, 43, 56, 72Functions can also return a value (or more than one value) to a caller. Consider the following program that adds a first and last name together into a full name.
-- Returning values.
local first_name = "Alice"
local last_name = "Johnson"
local function to_full_name(first, last)
return first .. " " .. last
end
local full_name = to_full_name(first_name, last_name)
io.write(full_name .. "\n")
io.write(to_full_name(first_name, last_name) .. "\n")
Some things to note in this program:
We use the keyword return to give a value back to the caller. The caller will
typically assign this value to a variable, or use it directly in an expression.
return is the last line the function will run, anything after it will be ignored.
Note also that the variables we pass in are called first_name and laast_name,
yet the arguments we specify in the function are first and last. Lua is clever
enough to map the variables to the arguments by the position in which they appear.
The names do not have to match!