Variables

Anonymous contributor's avatar
Anonymous contributor
Published Sep 18, 2023
Contribute to Docs

Variables are used to store data that can be referenced throughout the code.

Lua has two main types of variables: global variables, which can be used anywhere in a program, and local variables, which can only be referenced in the block where they’re defined.

Creating and Accessing Variables

A variable name can include letters, numbers, and underscores, but must begin with a letter or an underscore. A variable name cannot include a space or any other character. Variables do not need to be declared with a value, if a variable is called and it hasn’t been assigned a value it will return nil.

a = 10

After defining a variable, it can be referred to at any point in the code.

a = 10
print(a)

Lua also supports multiple assignment, such as in the example below.

b, c = "spam", "eggs"
print(c) -- This will print eggs

Scope

In Lua, a variable is assumed to be global unless it is explicitly declared as a local variable using the local keyword.

count = 2
function addValue (val)
local count = 1
return count + val
end
print(addValue(5)) -- Returns 6
print(count) -- Returns 2

Note: In the code above, if the local count = 1 statement is omitted the addValue() function will use the global value instead and return 7.

Reassigning Variables

To modify the value of a variable, assign a new value.

a = 10
print(a) -- This will print 10
a = 5
print(a) -- This will print 5

All contributors

Contribute to Docs

Learn Lua on Codecademy