Menu
CoddyTech

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.

The editor already has a helper, filter(list, keep): it calls keep(value) for every value and returns a new table with the values for which keep returned true. Call filter and pass the check as an anonymous function written directly in the call, the way the lesson passes one to table.sort(). Do not store the check in a variable or give it a name.

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)

Try it yourself

local function filter(list, keep)
    local result = {}
    for _, value in ipairs(list) do
        if keep(value) then
            table.insert(result, value)
        end
    end
    return result
end

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

Practice on your own: Online Lua compiler