Skip to content
AgileLogics
5 min read

Variables and local

Prerequisites: Your first program

A variable names a value so you can use it later.

local city = "Lagos"
local temperature = 24
print("It is " .. temperature .. " degrees in " .. city)

temperature = 27
temperature = temperature + 1
print(temperature)

local a, b, c = 1, 2
print(a, b, c)
a, b = b, a
print(a, b)
It is 24 degrees in Lagos
28
1	2	nil
2	1
  • local name = value creates a variable.
  • There's no += — write x = x + 1.
  • Multiple assignment: extra variables get nil; a, b = b, a swaps two values.

Always use local

Without local, a variable is global — visible everywhere, in every file:

local function setScore()
  score = 100      -- oops: no "local", so this creates a global
end

setScore()
print(score)
100

Globals are slower, easy to create by accident through a typo, and can clash between files and libraries. Declare every variable with local, and let a linter (luacheck or lua-language-server) warn you about globals. (Lua 5.5 adds a global keyword to declare globals explicitly.)

Naming

  • Names can contain letters, digits, and underscores, and can't start with a digit.
  • Names are case-sensitive: score and Score are different.
  • Common styles: snake_case (standard library) or camelCase (many game frameworks). Pick one and stay consistent.
  • Reserved words (and, end, function, local, nil, then, ...) can't be names.

Practice

Store a product name and a price in local variables and print Coffee costs 3.5.

Show solution
local product = "Coffee"
local price = 3.5
print(product .. " costs " .. price)
Coffee costs 3.5