Menu
Coddy logo textTech

Anonymous Functions

Part of the Logic & Flow section of Coddy's Lua journey — lesson 13 of 54.

Now that you understand functions can be stored in variables and passed around, there's an even more concise way to write them. Instead of always giving a function a name, you can create it directly where you need it—these are called anonymous functions.

An anonymous function is simply a function without a name. You define it using the function keyword followed immediately by its parameters and body:

function(a, b)
    return a + b
end

This creates a function value that can be used right away. Anonymous functions are particularly useful when passing functions as arguments to other functions. Remember the custom sorting example from earlier? Here's how it looks with an anonymous function:

local players = {
    {name = "Alice", score = 150},
    {name = "Bob", score = 200},
    {name = "Charlie", score = 175}
}

table.sort(players, function(a, b)
    return a.score > b.score
end)

Instead of defining a separate named function for the comparison, the function is created directly as the second argument to table.sort(). This makes the code more compact and keeps the sorting logic right where it's used.

challenge icon

Challenge

Easy

Write a function filterByThreshold that takes numbers and threshold and returns a new table containing only numbers greater than the threshold.

Use table.insert() with an anonymous function approach to filter the numbers. Create the filtering logic inline without defining a separate named function.

Logic:

  • Create an empty result table
  • Iterate through the numbers table
  • For each number, use an anonymous function to check if it exceeds the threshold
  • If the check returns true, add the number to the result table
  • Return the filtered result table

Parameters:

  • numbers (table): A list-style table containing numeric values
  • threshold (number): The minimum value (exclusive) for filtering

Returns: A table containing only numbers greater than the threshold (table)

Cheat sheet

An anonymous function is a function without a name, defined using the function keyword followed by parameters and body:

function(a, b)
    return a + b
end

Anonymous functions are useful when passing functions as arguments, keeping logic inline where it's used:

local players = {
    {name = "Alice", score = 150},
    {name = "Bob", score = 200},
    {name = "Charlie", score = 175}
}

table.sort(players, function(a, b)
    return a.score > b.score
end)

This creates the comparison function directly as an argument to table.sort(), making code more compact.

Try it yourself

function filterByThreshold(numbers, threshold)
    -- Write code here
end
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Logic & Flow