Declaring, Changing, and Accessing Variables - catwastakenwastaken/Roblox-LuaU-by-Example GitHub Wiki

In Lua(U), you can declare a variable a few different ways:

  • Locally -> Stored locally within the file, and cannot be accessed in other files

  • Globally -> Stored globally, and can be accessed in other files (Lua)

  • In _G -> Stored in the _G table (global table), and can be accessed by any file using _G.VariableName

  • In a Table (similar to _G) -> Stored as a Key-Value pair in a table (see Arrays & Dictionaries)

You may only use one equals sign when declaring a new variable or changing a variable's value.

e.g.

local foo = "foo" -- Local variable declaration

bar = "bar" -- Global variable declaration

_G.ReallyBigNumber = 12509815 -- Variable declaration in _G

local exampleTable = {
    VariableInTable = "Hello, world!", -- Variable declaration within another variable (see Arrays & Dictionaries)
}

By default, variable types are dynamic and inferred by the Lua(U) interpreter at runtime.

To access a variable, you refer to the variable's name or full path.

For example, when a variable is already declared earlier on in a script, it may be accessed at any time during runtime, except when the variable is declared within a sub-scope or a different scope. (see Code Blocks, Scopes, and Variable Shadowing)

print(foo) -- Outputs "foo"

print(bar) -- Outputs "bar"

print(_G.ReallyBigNumber) -- Outputs "12509815"

print(exampleTable.VariableInTable) -- Outputs "Hello, world!"

You can also dynamically change the variable's type and value during runtime by referring to the variable's name and declaring a new value.

foo = 1 -- number

bar = 2305.02 -- number

_G.ReallyBigNumber = {} -- Empty table

exampleTable.VariableInTable = "Hello!" -- string