Language
日本語
English

Caution

JavaScript is disabled in your browser.
This site uses JavaScript for features such as search.
For the best experience, please enable JavaScript before browsing this site.

  1. Home
  2. Lua Dictionary
  3. Function Definition

Function Definition

In Lua, functions are defined using the function keyword. There are multiple styles: global functions, local functions, anonymous functions, assignment to table fields, and method definition using colon syntax. This page covers each definition style and how to call them.

Syntax

-- -----------------------------------------------
-- Global function definition (most basic form)
-- -----------------------------------------------
function funcName(arg1, arg2)
    -- body
    return value           -- return is optional (returns nil when omitted)
end

-- -----------------------------------------------
-- Local function definition (recommended form with limited scope)
-- -----------------------------------------------
local function funcName(arg1, arg2)
    return value
end

-- -----------------------------------------------
-- Anonymous function (assigned to a variable)
-- -----------------------------------------------
local varName = function(arg1, arg2)
    return value
end

-- -----------------------------------------------
-- Function definition as a table field
-- -----------------------------------------------
local tableName = {}
tableName.funcName = function(arg)
    return value
end

-- Or defined at the time of declaration
local tableName = {
    funcName = function(arg)
        return value
    end,
}

-- -----------------------------------------------
-- Method definition using colon syntax (implicitly receives self)
-- -----------------------------------------------
function tableName:methodName(arg)
    -- self refers to the table itself
    return self.fieldName
end

-- -----------------------------------------------
-- Default argument pattern (Lua has no dedicated syntax for this)
-- -----------------------------------------------
local function funcName(arg1, arg2)
    arg2 = arg2 or defaultValue   -- apply default when arg2 is nil
    return arg1 + arg2
end

Syntax Reference

Syntax / FormDescription
function name(args) endDefines a function in global scope. Callable from anywhere in the file, but risks unintended name collisions.
local function name(args) endDefines a local function limited to the current scope. Commonly used to prevent unintended effects outside the scope.
local name = function(args) endAssigns an anonymous function to a variable. Treats functions as values; commonly used for callbacks and higher-order functions.
table.field = function(args) endAssigns a function to a table field. Used to create module-like or namespace structures.
function table:method(args) endDefines a method using colon syntax. self (the table itself) is implicitly passed as the first argument.
table:method(args)Calls a method using colon syntax. Automatically passes self; equivalent to table.method(table, args).
arg = arg or defaultDefault argument pattern. Since Lua has no dedicated syntax, the or operator is used to set a fallback value when the argument is nil.
return val1, val2Returns multiple values at once (multiple return values). The caller can receive them with local a, b = func().

Sample Code

kof_function_basic.lua
-- kof_function_basic.lua — Lua function definition and call sample
-- Uses KOF (The King of Fighters) characters to demonstrate
-- various function definition styles

-- -----------------------------------------------
-- Global function definition
-- -----------------------------------------------

-- Global function that receives character, move, and power and returns a string
function announceMove(character, move, power)
    return character .. "'s \"" .. move .. "\"! Power: " .. power
end

print("=== Global Function ===")
print(announceMove("Terry Bogard",  "Power Wave",   80))
print(announceMove("Andy Bogard",   "Zan'ei Ken",   85))
print("")

-- -----------------------------------------------
-- Local function definition (recommended form)
-- -----------------------------------------------

-- Local function that returns a rank based on power level
local function getRank(power)
    if power >= 95 then
        return "S Rank"
    elseif power >= 85 then
        return "A Rank"
    elseif power >= 75 then
        return "B Rank"
    else
        return "C Rank"
    end
end

print("=== Local Function ===")
print("Mai Shiranui (power: 88) -> " .. getRank(88))
print("Joe Higashi  (power: 82) -> " .. getRank(82))
print("")

-- -----------------------------------------------
-- Anonymous function (assigned to a variable)
-- -----------------------------------------------

-- Anonymous function that builds a victory message
local buildWinMessage = function(winner, loser)
    return winner .. " defeated " .. loser .. "!"
end

print("=== Anonymous Function ===")
print(buildWinMessage("Ralf Jones", "Clark Still"))
print("")

-- -----------------------------------------------
-- Function as table field (module-like structure)
-- -----------------------------------------------

-- Define a table for managing fighter information
local FighterUtil = {}

FighterUtil.formatProfile = function(name, team, power)
    return string.format("Name: %s  Team: %s  Power: %d  %s",
        name, team, power, getRank(power))
end

print("=== Table Field Function ===")
print(FighterUtil.formatProfile("Terry Bogard",  "Fatal Fury Team", 95))
print(FighterUtil.formatProfile("Ralf Jones",    "Ikari Team",      93))
print("")

-- -----------------------------------------------
-- Method definition using colon syntax
-- -----------------------------------------------

-- Define a fighter object
local fighter = {
    name  = "Mai Shiranui",
    team  = "Fatal Fury Team",
    power = 88,
    hp    = 100,
}

-- Define methods using colon syntax (self refers to the table itself)
function fighter:introduce()
    return self.name .. " (" .. self.team .. "). Nice to meet you!"
end

function fighter:takeDamage(damage)
    self.hp = self.hp - damage
    return self.name .. " took " .. damage .. " damage. Remaining HP: " .. self.hp
end

print("=== Colon Syntax Methods ===")
print(fighter:introduce())
print(fighter:takeDamage(30))
print(fighter:takeDamage(20))
print("")

-- -----------------------------------------------
-- Default argument pattern
-- -----------------------------------------------

-- Calculates move power. boost defaults to 1.0 when omitted
local function calcPower(base, boost)
    boost = boost or 1.0        -- apply default value 1.0 when nil
    return math.floor(base * boost)
end

print("=== Default Argument Pattern ===")
print("Power Wave (normal):     " .. calcPower(80))
print("Power Wave (boost 1.5x): " .. calcPower(80, 1.5))
print("Burn Knuckle (2.0x):     " .. calcPower(90, 2.0))
print("")

-- -----------------------------------------------
-- Multiple return values
-- -----------------------------------------------

-- Returns winner and loser simultaneously
local function battle(a, aPower, b, bPower)
    if aPower >= bPower then
        return a, b     -- first return value is winner, second is loser
    else
        return b, a
    end
end

print("=== Multiple Return Values ===")
local winner, loser = battle("Terry Bogard", 95, "Joe Higashi", 82)
print("Winner: " .. winner .. "  Loser: " .. loser)
lua kof_function_basic.lua
=== Global Function ===
Terry Bogard's "Power Wave"! Power: 80
Andy Bogard's "Zan'ei Ken"! Power: 85

=== Local Function ===
Mai Shiranui (power: 88) -> A Rank
Joe Higashi  (power: 82) -> B Rank

=== Anonymous Function ===
Ralf Jones defeated Clark Still!

=== Table Field Function ===
Name: Terry Bogard  Team: Fatal Fury Team  Power: 95  S Rank
Name: Ralf Jones    Team: Ikari Team       Power: 93  A Rank

=== Colon Syntax Methods ===
Mai Shiranui (Fatal Fury Team). Nice to meet you!
Mai Shiranui took 30 damage. Remaining HP: 70
Mai Shiranui took 20 damage. Remaining HP: 50

=== Default Argument Pattern ===
Power Wave (normal):     80
Power Wave (boost 1.5x): 120
Burn Knuckle (2.0x):     180

=== Multiple Return Values ===
Winner: Terry Bogard  Loser: Joe Higashi

Common Mistakes

Common Mistake 1: Mixing colon syntax and dot syntax

Calling a method defined with colon syntax using dot syntax results in self not being passed, causing unintended behavior. The reverse is also true.

ng_example.lua
local obj = { name = "Kiryu" }

function obj:greet()
    return "Hello, I am " .. self.name
end

-- Calling a colon-defined method with dot syntax
print(obj.greet())  -- self is not passed, so error
lua: ng_example.lua:4: attempt to index a nil value (local 'self')

Call a colon-defined method using colon syntax.

ok_example.lua
local obj = { name = "Kiryu" }

function obj:greet()
    return "Hello, I am " .. self.name
end

print(obj:greet())  -- call with colon syntax
Hello, I am Kiryu

Common Mistake 2: arg or default overwrites false

The arg = arg or default pattern replaces the value with the default not only when the argument is nil but also when it is false. It cannot be used for arguments where false is a valid value.

ng_example2.lua
local function setFlag(value)
    value = value or true  -- false gets replaced with true
    return value
end

print(setFlag(false))  -- intended false but gets true
print(setFlag(nil))    -- nil becomes true (as expected)
true
true

When false is also a valid value, use an explicit nil check.

ok_example2.lua
local function setFlag(value)
    if value == nil then
        value = true
    end
    return value
end

print(setFlag(false))  -- stays false
print(setFlag(nil))    -- becomes true
false
true

Overview

Lua functions are "first-class values." They can be assigned to variables, stored in table fields, and passed as arguments to other functions. There are five main definition styles: global functions, local functions, anonymous function assignments, table field assignments, and colon syntax methods. For limiting scope, local function or anonymous function assignment to a variable is standard. Global functions are used when you intentionally want to expose a symbol accessible across files. Colon syntax (function t:method()) is syntactic sugar that implicitly receives self as the first argument and is commonly used when writing object-oriented code. There is no dedicated syntax for default arguments; the idiom arg = arg or default is used. Lua also natively supports multiple return values with return a, b. Grouping functions in a table creates a module-like structure. For more, also see the Table Basics page.

If you find any errors or copyright issues, please .