Understanding Variables in Luau
Variables are esential in any programming language, and Luau, the language for Roblox scripting, is no exception. A variable acts as a container for storing information that your program can use later.
Declaring a Variable
To declare a variable in Luau, you use the local
keyword followed by the variable’s name and an optional value:
local myVariable = 10
In this example, myVariable
holds the value 10
.
Rules for Naming Variables
- A variable name must start with a letter or an underscore (
_
). - It can only include letters, numbers, and underscores.
- Reserved words like
local
,if
, orfunction
cannot be used as variable names. - Variable names are case-sensitive, so
myVariable
andMyVariable
are different.
Valid Examples
local playerScore
local _tempValue
local position2D
Invalid Examples
local 2ndValue -- Starts with a number
local if -- Reserved keyword
Types of Data in Variables
Variables can hold different types of data in Luau. Here are the main types:
-
Nil: Represents “nothing” or the absence of a value.
local myVariable = nil
-
Number: Stores numeric values like 25, -10, or 3.14.
local age = 25
-
String: Holds text enclosed in quotes.
local playerName = "Alex"
-
Boolean: Stores
true
orfalse
values.local isAlive = true
-
Table: A collection of data, like a list.
local inventory = {"sword", "shield", "potion"}
-
Function: A block of code that can be executed (‘called’) later.
local greet = function() print("Hello!") end -- To call greet, we do greet()
-
Instance: Refers to Roblox objects, like parts or players.
local part = workspace.Part
-
You can find all types here, just click the ‘types’ tab on the left side:
Luau | Documentation - Roblox Creator Hub
Dynamic Typing
Luau is dynamically typed, meaning a variable’s type can change during runtime. For example:
local myVariable = 42
myVariable = "Hello, World!" -- This is allowed
Variable Scope
In Luau, variables can be categorized based on their scope:
-
Global Variables: Declared without
local
. These can be accessed anywhere in the script but are generally discouraged as they may cause unexpected behavior.myVariable = 20
-
Local Variables: Declared with
local
. These are safer and only accessible within the part of the code where they are defined.
Scope Example
local function example()
local localVar = 10 -- Only accessible inside this function
globalVar = 20 -- Accessible anywhere in the script
end
example()
print(globalVar) -- Prints 20
print(localVar) -- Error: localVar is not defined here
Common Errors with Variables
-
Using a Reserved Word: Reserved words cannot be used as variable names.
local if = 10 -- Error
-
Syntax Error: Occurs when you forget
local
or write something incorrectly.local 2value = 10 -- Error
-
Type Mismatch: Happens when you use a variable in a way that doesn’t match its type.
local has_score = true print(has_score+ 5) -- attempt to perform arithmetic (add) on boolean and number