Functions
237
In Lua you define a function in the following way:
function hello()
print("Hello!")
end
hello()
A function, as usual, can have parameters:
function hello(name)
print("Hello, " .. name)
end
hello("Sam")
To return a value from a function you use return
statement:
function sum(a, b)
return a + b
end
print(sum(10, 20))
A function can return multiple values with comma-separated list:
function person()
return "Sam", "samblog.com", 100
end
name, website, wallet = person()
print(name)
print(website)
print(wallet)
A function can have multiple return statements as well:
function older_person(name1, age1, name2, age2)
if age1 > age2 then
return name1
elseif age2 > age1 then
return name2
else
return "Noone"
end
end
print(older_person("Peter", 25, "Alice", 20) .. " is older")
There are also anonymous functions which you can store in variables and pass as function arguments:
function for_each(list, f)
for n = 1, #list do
f(list[n])
end
end
names = {"Peter", "Alice", "Michael", "Tiffany"}
for_each(names, function(name)
print("Hello, " .. name)
end)
sum = function(a, b)
return a + b
end
print(sum(1, 2))
There is a simple syntax for variable length parameters list:
function sum(...)
result = 0
for i, v in ipairs({...}) do
result = result + v
end
return result
end
print(sum(10, 20, 30))
You can think of ...
as a simple replacement of the actual parameters list. For example, you can write something like this:
function sum(...)
v1, v2, v3 = ...
return v1 + v2 + v3
end
print(sum(10, 20, 30))
Rate this post:
Lesson 6
Lesson 8
Share this page:
Learning plan
4. Data types
A list of data types and their descriptions which Lua operates on
5. Operators
A list of built-in operators in Lua
6. Control flow
A list of Lua statements which you use to organize control flow of a program
7. Functions
What kind of functions are there and how to write them
How to write tail recursion in Lua properly
9. Strings
How to define and work with strings
10. Arrays
How to deal with arrays or lists