Skip to content
Tutorials Center
My learning

Topics

Lesson 3 of 32 ยท Getting Started

Variables and Types

Learn Lua variables and the eight basic types: local versus global, nil, booleans, numbers, strings, tables, functions, type() and multiple assignment.

A variable is a name that refers to a value. Lua is dynamically typed: the variable has no type, the value does. You can store a number in a name and later store a string in the same name, and Lua will not complain. This freedom is convenient, but it means you need to know exactly which kinds of values exist and how to ask a value what it is.

This lesson covers declaring variables with local, the dangerous alternative (globals), the eight basic types, the type() function, and multiple assignment. You can follow along in a terminal with lua, or use the JavaScript stand-ins here. If you need a refresher on running scripts, see Your First Lua Program.

Declaring variables: local and global

Use the keyword local to create a variable that exists only in the block where you declare it.

LUA
local score = 10
local name = "Ada"
score = score + 5
print(name, score)   --> Ada	15

If you assign to a name without local, Lua creates a global variable. Globals live in a shared table and are visible from every file and function.

LUA
counter = 0          -- global (usually a mistake)
local total = 0      -- local (preferred)

Globals are almost always a bug in disguise. A typo such as scroe = 5 silently creates a new global instead of failing. Use local for everything unless you have a clear reason not to. Reading a global that was never set is not an error either: it just gives nil.

LUA
print(missing)       --> nil

Locals are also faster to access than globals, and they obey block scope: a local declared inside do ... end, a loop, an if or a function disappears when that block ends.

LUA
local x = 1
do
  local x = 2        -- a new variable that shadows the outer x
  print(x)           --> 2
end
print(x)             --> 1

Lua 5.4 adds two attributes. local limit <const> = 100 makes a constant that cannot be reassigned (the compiler rejects an assignment to it). <close> is for resources that should be released automatically and is covered in Error Handling.

The eight basic types

Lua has exactly eight types.

Simple values

nil The absence of a value.
boolean true or false.
number Integers and floats.
string Immutable text.
1 / 2
  • nil means "nothing here". An unset variable is nil, and assigning nil to a table field removes it.
  • boolean has two values, true and false.
  • number covers both integers and floating-point numbers, using the same type name. In Lua 5.4 each number is internally an integer or a float, and math.type tells them apart. See Numbers and the math Library.
  • string is a sequence of bytes. Strings are immutable. See Strings.
  • table is the one data structure. See Tables as Arrays and Dictionaries.
  • function values are first class: you can store them in variables, pass them as arguments and return them.
  • thread is what Coroutines are made of. It has nothing to do with operating system threads.
  • userdata is a value created by the host program (usually in C) that Lua can hold but not look inside, such as a file handle.

Asking for the type

The function type returns the type name as a string.

LUA
print(type(nil))          --> nil
print(type(true))         --> boolean
print(type(42))           --> number
print(type(3.14))         --> number
print(type("hello"))      --> string
print(type({}))           --> table
print(type(print))        --> function
print(type(type))         --> function
print(type(type(1)))      --> string

Notice that type(nil) returns the string "nil", which is different from the value nil. Comparing against the string is the usual way to check a type.

LUA
local function describe(v)
  if type(v) == "number" then
    return "a number"
  end
  return "something else"
end

For integer versus float, use math.type, which returns "integer", "float", or nil for anything that is not a number.

LUA
print(math.type(1))       --> integer
print(math.type(1.0))     --> float
print(math.type("1"))     --> nil

Dynamic typing and coercion

Because values carry the type, the same variable can hold anything over time.

LUA
local v = 10
v = "ten"
v = { 10 }
v = nil

Lua converts between strings and numbers automatically in arithmetic, but not in comparisons.

LUA
print("10" + 5)           --> 15
print("3" * "4")          --> 12
print(10 == "10")         --> false
print(10 .. 20)           --> 1020

The string "10" is turned into a number for +, but 10 == "10" is false because the two values have different types. Rely on explicit tonumber and tostring in real code, which is clearer. Arithmetic on a string that does not look like a number raises an error: "abc" + 1 fails with "attempt to perform arithmetic on a string value".

Multiple assignment

Lua can assign several variables in one statement. All the right-hand expressions are evaluated first, and then the assignments happen.

LUA
local a, b = 1, 2
a, b = b, a               -- swap
print(a, b)               --> 2	1

local x, y, z = 10, 20    -- z is nil (missing values become nil)
local p, q = 1, 2, 3      -- 3 is dropped (extra values are discarded)

Swapping with a, b = b, a needs no temporary variable. This works with table fields too: t[i], t[j] = t[j], t[i] swaps two elements, a pattern you will use constantly when sorting. Functions can also return several values at once, which is covered in Functions.

Stand-ins you can run

JavaScript has no integer/float split, no nil and no tables, but we can write a small helper that reports Lua-style type names for JavaScript values. This is a model for learning, not real Lua behavior.

JS Lua-style type() for JavaScript values (stand-in)

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The second stand-in shows multiple assignment and shadowing, using JavaScript destructuring and block scope.

JS Multiple assignment and scope (stand-in)

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What happens if you assign to score = 5 without local inside a function?

    Without local, assignment targets a global variable. That is why unintended globals are a common source of bugs.
  2. 2. What does print(type(nil)) print?

    type always returns a string, so type(nil) is the string "nil", which print shows as nil.
  3. 3. After local a, b = 1, 2; a, b = b, a, what are a and b?

    The right-hand side is evaluated first, then the values are assigned, so the two variables swap.
  4. 4. What is the value of 10 == "10" in Lua?

    Equality does not convert strings to numbers. Values of different types are never equal.
  5. 5. How many basic types does Lua have?

    nil, boolean, number, string, table, function, thread and userdata.

Summary

  • Declare variables with local; assignment without it creates a global, which is usually a bug.
  • Lua has eight types: nil, boolean, number, string, table, function, thread and userdata.
  • type(v) returns the type name as a string; math.type separates integers from floats.
  • Variables are untyped; values carry their type, and strings convert to numbers in arithmetic but not in ==.
  • Multiple assignment evaluates the right side first, so a, b = b, a swaps; missing values become nil and extras are dropped.

Next: work with numbers in Numbers and the math Library.