Skip to content
Tutorials Center
My learning

Topics

Lesson 8 of 37 ยท Luau Scripting

Luau Variables and Types

Learn Luau variables with local, the basic types (number, string, boolean, nil, table, function), Roblox types like Vector3 and Color3, typeof, scope and naming rules.

A variable is a name for a value. Scripting is mostly about storing values (a player's score, a part, a speed), looking at them, and changing them. This lesson covers how to create variables in Luau, the types of values they can hold, and the extra types Roblox adds for 3D work.

Creating variables

Use the keyword local followed by a name, an equals sign and a value:

LUA
local score = 0
local playerName = "Mira"
local isAlive = true

score = score + 10    -- change it later (no `local` this time)
print(playerName, score, isAlive)  --> Mira 10 true

Always write local. Without it you create a global variable that any script in the same environment may read or overwrite, which is slower and a classic source of bugs. Studio underlines accidental globals.

Names may contain letters, digits and underscores, cannot start with a digit, and are case sensitive: score and Score are different. The usual styles are camelCase for variables and functions and PascalCase for services, classes and constants such as MAX_SPEED (SCREAMING_SNAKE_CASE). Choose descriptive names: jumpHeight beats jh.

Luau also has compound assignment, a shortcut for updating a variable:

LUA
local coins = 5
coins += 3   -- same as coins = coins + 3
coins -= 1
coins *= 2
print(coins) --> 14

The basic types

Luau has a small number of built-in types.

Type Examples Notes
number 42, 3.14, -7, 1e3 One type for integers and decimals (64-bit float)
string "hello", 'hi' Text; see the strings lesson
boolean true, false Only these two values
nil nil "No value"; the default for anything unset
table {1, 2, 3}, {name = "A"} Lists and records; see tables
function function() end Functions are values
thread made with coroutine Used by task.spawn and friends
userdata Vector3, Instance... Types supplied by the engine

Check a type with type(), or better, typeof(), which also understands Roblox's own types:

LUA
print(typeof(10))                 --> number
print(typeof("hi"))               --> string
print(typeof(nil))                --> nil
print(typeof({}))                 --> table
print(typeof(Vector3.new(1,2,3))) --> Vector3
print(typeof(workspace))          --> Instance
print(type(Vector3.new(1,2,3)))   --> userdata

Numbers

Numbers are floating-point. 7 / 2 is 3.5; use // for floor division (7 // 2 is 3). Useful built-ins live in the math library: math.floor, math.ceil, math.round, math.abs, math.sqrt, math.max, math.min, math.clamp, math.random, math.pi and math.huge (infinity). Angles in Roblox APIs are mostly in radians; convert degrees with math.rad(deg).

LUA
print(math.clamp(150, 0, 100)) --> 100
print(math.floor(7.9))         --> 7
print(math.random(1, 6))       -- a random die roll

Floating-point caveat: 0.1 + 0.2 is 0.30000000000000004. Do not compare decimals with ==; compare against a small tolerance.

nil: the absence of a value

nil means nothing is there. Reading a variable that was never set gives nil; setting a variable to nil clears it. nil is the most common source of errors in Roblox: a script expects a part and gets nil.

LUA
local coin = workspace:FindFirstChild("Coin")
print(coin)          -- nil if there is no part named Coin
print(coin.Name)     -- error: attempt to index nil with 'Name'

Always guard: if coin then ... end. In conditions, only nil and false count as false. Note that 0 and "" are truthy in Luau, unlike in JavaScript.

Roblox types

Roblox adds types for 3D and appearance. They are created with a constructor function, never with new as a keyword.

LUA
local position = Vector3.new(0, 10, 0)             -- x, y, z in studs
local color = Color3.fromRGB(255, 170, 0)          -- 0-255
local twoD = Vector2.new(100, 50)                  -- for UI
local where = CFrame.new(0, 5, 0)                  -- position and rotation
local material = Enum.Material.Wood                -- a named option
local info = TweenInfo.new(2)                      -- tween settings

Vector3 and Color3 appear everywhere in later lessons; Vectors and CFrames covers them in depth. Enums are fixed sets of named choices, such as Enum.Material.Neon. Use the enum rather than a number or string because it autocompletes and cannot be mistyped.

Scope

A local variable exists from its declaration to the end of the block it was declared in (a block is the body of a function, if, loop or the whole script).

LUA
local x = 1
do
	local y = 2        -- y exists only inside this do...end
	print(x, y)        --> 1 2
end
print(x, y)            --> 1 nil   (y is out of scope; it is read as a global and is nil)

Declare variables in the smallest scope that works. Shadowing (reusing a name in an inner block) is legal but confusing; avoid it.

Constants

Luau has no const keyword, but a naming convention makes intent clear:

LUA
local MAX_PLAYERS = 12
local GRAVITY_SCALE = 0.5

You can also freeze a table to prevent edits (see tables).

A stand-in: types and typeof

Real Luau reports its own type names. This JavaScript stand-in imitates typeof for a handful of values so you can see how a type name is chosen, including the difference between nil and an object. Edit the list and run it again.

JS Stand-in: a typeof for Luau-like values (JavaScript)

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

No output.

A stand-in: truthiness

In Luau, only nil and false are false. Everything else, including 0 and the empty string, is true. JavaScript differs, so this stand-in shows the Luau rule:

JS Stand-in: Luau truthiness (JavaScript)

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

No output.

Look at the rows for 0 and "": Luau says true, JavaScript says false. That difference trips up many learners who already know JavaScript.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Which keyword should you use for almost every variable?

    local keeps the variable in its own scope. Without it you create a global.
  2. 2. What does typeof(Vector3.new(1,2,3)) return?

    typeof understands Roblox's own types and returns Vector3. Plain type() would say userdata.
  3. 3. Which values are false in a Luau condition?

    In Luau only nil and false are falsy. Zero and the empty string count as true.
  4. 4. What does workspace:FindFirstChild("Missing") return when no such child exists?

    FindFirstChild returns nil when nothing is found, so check before using the result.
  5. 5. What does coins += 3 do?

    Compound assignment is shorthand for coins = coins + 3.

Summary

  • Create variables with local; use clear camelCase names; += and friends shorten updates.
  • Types: number, string, boolean, nil, table, function, thread and userdata (including Roblox types).
  • Use typeof to learn a type; only nil and false are falsy.
  • Roblox types (Vector3, Color3, CFrame, Enum) are made with constructors.
  • Variables live in the block where they are declared.

Next: Strings and Operators