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
endThis 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
EasyWrite 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 valuesthreshold(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
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Logic & Flow
1Advanced Table Iteration
Iterating with pairs()Iterating with ipairs()pairs() vs. ipairs()Recap - Character Sheet2More Table Library Functions
table.concat()table construction & unpack()table.sort()Custom Sorting with FunctionsRecap - High Score Board3Advanced Function Concepts
Returning Multiple ValuesVariadic Functions (...)Functions First-Class ValuesAnonymous FunctionsWhat is a Closure?Recap - Simple Event HandlerPractice on your own: Online Lua compiler