Learn Lua in Neovim: Functions — Basics, Parameters vs Arguments & return | Episode 12
Video: Learn Lua in Neovim: Functions — Basics, Parameters vs Arguments & return | Episode 12 by Taught by Celeste AI - AI Coding Coach
Watch full page →Learn Lua in Neovim: Functions — Basics, Parameters vs Arguments & return
Functions in Lua let you write reusable blocks of code that can be called with different inputs. In this tutorial, you'll learn how to define functions using function and end, how to use parameters as placeholders, pass arguments when calling functions, and return values back to the caller. These basics help you avoid repetition and write cleaner Neovim Lua configurations.
Code
-- Define a function named greet with one parameter 'name'
function greet(name)
-- Return a greeting string using the parameter
return "Hello, " .. name .. "!"
end
-- Call greet with argument "Celeste" and print the result
print(greet("Celeste")) -- Output: Hello, Celeste!
-- Define a function add with two parameters 'a' and 'b'
function add(a, b)
-- Return the sum of a and b
return a + b
end
print(add(5, 7)) -- Output: 12
-- Define a function to check if a number is even
function is_even(n)
-- Return true if n modulo 2 equals 0, else false
return n % 2 == 0
end
print(is_even(4)) -- Output: true
print(is_even(5)) -- Output: false
Key Points
- Use
function name(params)...endto define reusable functions in Lua. - The
returnstatement sends a value back to the caller. - Parameters are placeholders defined in the function; arguments are actual values passed during calls.
- Functions can return any Lua value, including strings, numbers, booleans, or nothing.
- Call functions using
name(arg1, arg2)syntax to execute with specific inputs.