It's time to take a more detailed look at values, and something known as a type.
So far we have seen a few sorts of values - string, number, boolean, and the special
value nil. These values each have a type associated with them. The following
Lua program prints out the type for a set of values, including a couple we will
meet in future lessons.
-- Values and types.
io.write(type("A") .. "\n")
io.write(type("A longer string") .. "\n")
io.write(type(10) .. "\n")
io.write(type(10.0) .. "\n")
io.write(type(true) .. "\n")
io.write(type(false) .. "\n")
io.write(type(nil) .. "\n")
io.write(type(io.write) .. "\n")
io.write(type(io) .. "\n")
Running this program produces the following output:
string
string
number
number
boolean
boolean
nil
function
table
The function type tells us the type of the value we pass to it. What happens
if we pass a variable to the call to type instead of a literal value?
local variable = "a string"
io.write(type(variable) .. "\n")
We get the output string, because that is the type of the value referred to by
the variable. This is an important subtlety of Lua, variables do not have types,
values do. We can see this in the following program:
local variable = "a string"
io.write(type(variable) .. "\n")
variable = 100
io.write(type(variable) .. "\n")
variable = false
io.write(type(variable) .. "\n")string
number
boolean
It looks like the variable is changing its type, but it is not. A variable has no type, it is just like a sticky note affixed to a value. The value has the type.
Now we have a better understanding of types and variables, it's time to look at Lua's one and only data structure, the table. The next few lessons will explore this versatile type, showing you how to store lists and maps of values.