Title here
Summary here
Functions are central in Lua. We’ll learn about functions with a few different examples.
-- Here's a function that takes two numbers and returns their sum
function plus(a, b)
return a + b
end
-- In Lua, you don't need to specify parameter types or return types
function plusPlus(a, b, c)
return a + b + c
end
-- The main function in Lua is typically just the script itself,
-- but we'll wrap it in a function for consistency
function main()
-- Call a function just as you'd expect, with name(args)
local res = plus(1, 2)
print("1+2 =", res)
res = plusPlus(1, 2, 3)
print("1+2+3 =", res)
end
-- Call the main function
main()
To run the program, save it as functions.lua
and use the lua
command:
$ lua functions.lua
1+2 = 3
1+2+3 = 6
There are several other features to Lua functions. One is multiple return values, which we’ll look at next.
Key differences from the original example:
function
keyword to declare functions instead of func
.local
keyword is used for variable declarations within functions.--
for comments instead of //
.main
function. Scripts are executed from top to bottom, but we’ve wrapped the main code in a function for similarity.print
function for output instead of fmt.Println
.+
operator.These changes reflect the idiomatic way of writing Lua code while maintaining the structure and purpose of the original example.