LU Lua

Lua: Variables & Data Types

What you will learn

Lua is dynamically typed. Variables are global by default — this is different from most languages and can cause bugs if you're not careful.

name = "Alice"       -- string
age = 25             -- number (all numbers are double)
is_student = true    -- boolean
local score = 100    -- local variable (scoped to block)

Global vs local

  • Variables without local are global — accessible everywhere in the program.
  • Variables with local exist only within the block where they're declared (function, loop, chunk). Always use local unless you explicitly need global scope.

nil — the absence of a value

nil represents "no value." Accessing an undefined variable returns nil, not an error:

print(x)        -- nil (not an error!)
local y = nil  -- explicit nil assignment

Dynamic typing

Lua has eight basic types, but only a few are commonly used:

Type Example Notes
nil nil No value
boolean true, false Lowercase
number 42, 3.14 Double-precision, no separate int
string "hello", 'world' Immutable
table {1, 2, 3} The only data-structure type
function function() end First-class functions

Common mistakes

  • Forgetting local and accidentally creating a global variable inside a function.
  • Using nil in a table index — t[nil] is not a valid table access.
  • Confusing false with nil — both are falsy, but false is a value while nil means absent.

Quick check below!