Defining and calling functions
A function is a named block of code you can run whenever you need it.
In this page:
Defining and calling functions
Define a function with function name(params) ... end and call it with parentheses. Functions are values, so the definition is shorthand for assigning to a variable. Prefer local function so the function is not global. If a call has a single string or table literal argument the parentheses may be omitted.
Note:
A function without a return statement returns no values at all.
Example: Defining and calling functions
local function greet(name)
return "Hello, " .. name
end
print(greet("Lua"))
print(type(greet))
local function noReturn() end
print(noReturn())
print(#"abc", type{})
-- Output:
-- Hello, Lua
-- function
--
-- 3 table
Login to try C/C++/Java/PHP code in the editor
Common Mistakes
- Forgetting the parentheses when calling and getting the function itself
- Defining functions globally by accident
- Missing end at the close of the function
Chapter Summary
- Use function name(...) end
- Prefer local function
- Call with parentheses
- No return means no value
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: