Learn Lua in Neovim: Variable Scope — local Keyword, Block Scope & Always Use Local | Episode 14
Video: Learn Lua in Neovim: Variable Scope — local Keyword, Block Scope & Always Use Local | Episode 14 by Taught by Celeste AI - AI Coding Coach
Watch full page →Learn Lua in Neovim: Variable Scope — local Keyword, Block Scope & Always Use Local
Understanding variable scope in Lua is crucial for writing clean and bug-free code in Neovim configuration and plugins. This guide explains the difference between local and global variables, demonstrates block scoping in constructs like for loops and if statements, and shows how variable shadowing works. You'll also learn why always declaring variables as local helps avoid subtle bugs in larger projects.
Code
-- Global variable (no 'local' keyword)
x = 10
-- Local variable, visible only within this block
local y = 20
print("Global x:", x) -- prints 10
print("Local y:", y) -- prints 20
-- Block scope example with 'if'
if true then
local y = 30 -- shadows outer 'y' inside this block
print("Inner block local y:", y) -- prints 30
end
print("Outer y after block:", y) -- prints 20, outer 'y' unchanged
-- Block scope example with 'for' loop
for i = 1, 3 do
local x = i * 2 -- local to this loop iteration
print("Loop local x:", x)
end
print("Global x after loop:", x) -- still 10, loop 'x' was local
-- Function scope and shadowing
local function demo()
local x = 100 -- shadows global 'x' inside function
print("Function local x:", x)
end
demo()
print("Global x outside function:", x)
Key Points
- The
localkeyword restricts a variable's visibility to its enclosing block, preventing unintended access. - Variables declared without
localare global and accessible everywhere, which can lead to conflicts and bugs. - Each block—such as
forloops,ifstatements, and functions—creates its own scope for local variables. - Variable shadowing occurs when a local variable in an inner block uses the same name as one in an outer scope, temporarily hiding the outer variable.
- Always declare variables with
localto avoid silent, hard-to-debug issues caused by accidental global variables.