← Back to Lua Course | Chapter 2: Variables & Types | Lesson 1 of 7

Variables and assignment

A variable is a name that holds a value, and you can change what it holds at any time.

In this page:

  1. Variables and assignment

Variables and assignment

Assign with a single equals sign. Variables have no declared type, only values do, so the same variable can hold a number and later a string. Lua supports multiple assignment, so a, b = b, a swaps two values without a temporary.

Note: Names are case sensitive and may contain letters, digits and underscores but cannot start with a digit.

Example: Variables and assignment

lua
local x = 10
x = "now a string"
print(x)

local a, b = 1, 2
a, b = b, a
print(a, b)

local p, q, r = 1, 2
print(p, q, r)

-- Output:
-- now a string
-- 2	1
-- 1	2	nil
Common Mistakes
  1. Using a reserved word like end or function as a name
  2. Expecting a declared type to be enforced
  3. Assuming a, b = 1 gives b the value 1
Chapter Summary
  • Assign with =
  • Variables hold any type
  • Multiple assignment swaps values
  • Missing values become nil
🔒

Chapter Quiz — Complete all 7 topics to unlock

0/7 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.