BudiBadu Logo
Samplebadu

Lua by Example: Variables

Lua 5.4

Lua is dynamically typed. This sample demonstrates global and local variable declarations and basic types.

Code

-- Global variable (default)
name = "Lua"

-- Local variable (recommended)
local version = 5.4

-- Multiple assignment
local x, y, z = 10, 20, 30

-- Nil type (absence of value)
local empty = nil

-- Dynamic typing
local value = 100
print(type(value)) -- number
value = "Changed"
print(type(value)) -- string

print("Language: " .. name .. " " .. version)

Explanation

Lua is a dynamically typed language, meaning variables do not have types; only values do. There are eight basic types in Lua: nil, boolean, number, string, userdata, function, thread, and table. Variables are global by default, which can lead to unexpected behavior in larger programs. It is best practice to use the local keyword to define variables with a limited scope.

Lua supports multiple assignment, allowing you to assign values to multiple variables in a single line, like x, y = 1, 2. This feature is particularly useful for swapping values (x, y = y, x) or capturing multiple return values from a function. If there are more variables than values, the extra variables are assigned nil.

The nil type is special; it represents the absence of a useful value. Assigning nil to a global variable is equivalent to deleting it. Lua treats both nil and false as false in conditions; everything else (including 0 and empty strings) is treated as true.

Code Breakdown

5
local version = 5.4 restricts the variable's scope to the current block or chunk.
17
.. is the string concatenation operator. Unlike other languages that use +, Lua uses two dots.