← Back to Lua Course | Chapter 5: Functions | Lesson 1 of 7

Defining and calling functions

A function is a named block of code you can run whenever you need it.

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

lua
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
Common Mistakes
  1. Forgetting the parentheses when calling and getting the function itself
  2. Defining functions globally by accident
  3. 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

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.