Data Types
Prerequisites: Variables and local
Lua has eight types. type() tells you which one a value has:
print(type(nil))
print(type(true))
print(type(42))
print(type("hello"))
print(type({}))
print(type(print))
print(type(coroutine.create(function() end)))
print(type(io.stdout))
nil
boolean
number
string
table
function
thread
userdata
| Type | Holds |
|---|---|
nil |
"no value" |
boolean |
true or false |
number |
integers and floating-point numbers |
string |
text (immutable) |
table |
the one data structure: arrays, dictionaries, objects |
function |
functions are values |
thread |
a coroutine (Level 2) |
userdata |
data from C, like an open file |
Dynamic typing
Variables don't have types; values do. A variable can hold a number now and a string later:
local x = 10
print(type(x))
x = "ten"
print(type(x))
number
string
That's flexible but means mistakes show up only when the code runs.
lua-language-server can catch many of them early using type annotations
in comments (---@param name string).
Converting
print(tonumber("42") + 1)
print(tonumber("3.5"))
print(tonumber("abc"))
print(tonumber("ff", 16))
print(tostring(42) .. "!")
print("10" + 5)
print(10 .. 5)
43
3.5
nil
255
42!
15
105
tonumberreturnsnilwhen a string isn't a number — check for it.- Lua converts automatically in arithmetic (
"10" + 5is15) and in concatenation (10 .. 5is"105"— note the spaces around..with numbers). Relying on automatic conversion is considered poor style; convert explicitly.