Variables & Data Types in Lua
Lua is a dynamically typed language, which means variables don't have types, only values do. In this tutorial, we'll explore Lua's variable system and its basic data types.
Variable Declaration
In Lua, variables are global by default. To create a local variable, use the local
keyword:
-- Global variable
globalVar = 10
-- Local variable
local localVar = 20
Basic Data Types
Lua has eight basic types:
nil
- represents the absence of a valueboolean
- true or falsenumber
- represents both integers and floatsstring
- sequence of charactersfunction
- reusable code blocksuserdata
- allows C data to be stored in Lua variablesthread
- independent threads of executiontable
- the only data structure in Lua (arrays, dictionaries, objects)
Type Function
You can check a value's type using the type()
function:
print(type("Hello")) -- string
print(type(10.4)) -- number
print(type(print)) -- function
print(type(true)) -- boolean
print(type(nil)) -- nil
Strings
Strings can be enclosed in single or double quotes:
local str1 = "Hello"
local str2 = 'World'
local multiLine = [[
This is a multi-line
string in Lua
]]
Tables
Tables are Lua's only data structure but are incredibly flexible:
-- Array-like table
local arr = {10, 20, 30}
-- Dictionary-like table
local dict = {name = "Lua", version = "5.4"}
Next Steps
Now that you understand variables and data types, learn about control structures in Lua.