Variables & Data Types in Luau
Understanding Variables in Luau
In Luau, variables are used to store data that can be referenced and manipulated throughout your scripts. There are two main types of variables: local and global.
Local Variables
Local variables are declared using the local keyword and are only accessible within the block of code where they are defined. This helps to prevent naming conflicts and keeps your code organized.
local myVariable = 10
In this example, myVariable is a local variable that holds the number 10.
Global Variables
Global variables, on the other hand, are accessible from anywhere in your script. You can create a global variable by simply assigning a value without using the local keyword.
myGlobalVariable = "Hello, World!"
This creates a global variable myGlobalVariable that can be accessed from any part of your script.
Core Data Types in Luau
Luau supports several core data types that you will frequently use while scripting in Roblox:
- nil: Represents the absence of a value.
- boolean: A truth value that can either be
trueorfalse. - number: Represents numeric values, including integers and floating-point numbers.
- string: A sequence of characters, enclosed in either single or double quotes.
- table: A data structure that can hold multiple values, similar to arrays or dictionaries in other languages.
- function: A block of code that can be executed when called.
Examples of Core Data Types
Here are some examples of each core data type:
local myNil = nil
local myBoolean = true
local myNumber = 42
local myString = "Hello"
local myTable = {1, 2, 3}
local myFunction = function() print("Hello from a function!") end
Common Roblox Data Types
In addition to core data types, Roblox has several specific types that are commonly used in game development:
- Vector3: Represents a point in 3D space with X, Y, and Z coordinates.
- CFrame: Represents the position and orientation of an object in 3D space.
- Color3: Represents a color in RGB format.
- Instance: Represents objects in Roblox, such as parts, models, and scripts.
Examples of Roblox Data Types
Here are examples of how to create instances of these types:
local myVector = Vector3.new(1, 2, 3)
local myCFrame = CFrame.new(0, 5, 0)
local myColor = Color3.fromRGB(255, 0, 0)
local myPart = Instance.new("Part")
Assigning Values to Variables
To assign a value to a variable, use the assignment operator =. You can change the value of a variable at any time by reassigning it.
local score = 0
score = score + 1 -- Increment score by 1
In this example, we start with a score of 0 and increase it by 1.
Conclusion
Understanding variables and data types is crucial for effective scripting in Luau. By utilizing local and global variables appropriately and knowing how to work with core and Roblox-specific data types, you can create more dynamic and functional scripts for your games.