# 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