Learn Lua in Neovim: First-Class Functions — Store, Pass & Filter with Functions | Episode 15
Video: Learn Lua in Neovim: First-Class Functions — Store, Pass & Filter with Functions | Episode 15 by Taught by Celeste AI - AI Coding Coach
Watch full page →Learn Lua in Neovim: First-Class Functions — Store, Pass & Filter with Functions
In Lua, functions are first-class values, meaning you can store them in variables, pass them as arguments, and return them from other functions. This flexibility enables powerful patterns like callbacks, anonymous functions, and higher-order functions such as filters that select items from lists.
Code
-- Store a function in a variable that squares a number
local square = function(x)
return x * x
end
print("5 squared is", square(5)) -- Output: 5 squared is 25
-- Define a function that takes another function and a value, then applies the function to the value
local function apply(func, value)
return func(value)
end
print("Square of 6 is", apply(square, 6)) -- Output: Square of 6 is 36
print("Square root of 25 is", apply(math.sqrt, 25)) -- Output: Square root of 25 is 5
-- Use an anonymous function to filter even numbers from a list
local function filter(items, test)
local result = {}
for _, item in ipairs(items) do
if test(item) then
table.insert(result, item)
end
end
return result
end
local numbers = {1, 2, 3, 4, 5, 6}
local evens = filter(numbers, function(n) return n % 2 == 0 end)
print("Even numbers:")
for _, v in ipairs(evens) do
print(v) -- Outputs: 2, 4, 6
end
Key Points
- Functions can be stored in variables just like any other data type in Lua.
- Passing functions as arguments (callbacks) allows flexible and reusable code.
- Anonymous functions let you define behavior inline without naming the function.
- Higher-order functions like
filterdemonstrate the power of first-class functions. - These patterns form the foundation for closures and functional programming in Lua.