Home | About | Forum | Manual | Download | Screenshots

Data types

You should know by now that all the data in your program is stored in memory and is accessed through variables. This data could be of several types, it could be text, a number or something else. Until you assign some value to a variable, it is considered "uninitialized" or "nil". The semantics of the value which you are assigning determines the variable's type. For example, the value of "10" is considered a string whereas 10 is a number. As you previously learned, anything enclosed in quotation marks is interpreted by the parser as a string.

Conversion

Consider a variable called var to which we assign the literal string value of "10". From that point on, the parser will tacitly assume that var is a string instead of a number because when specifying its value we explicitly put it in quotation marks. How can we extract the actual number 10 from our string variable? The process is called "conversion" and as you can see from the examples, it is much easier in Lua than in declarative languages like C.

var = "10"

-- convert var into a number
var = tonumber ( var )

-- convert var into a string again
var = tostring ( var )

Coercion

Lua is smart enough to automatically handle operations that involve multiple data types. Check out the following example of creating a string variable and then dividing it by a number. Since division is a mathematical operation, Lua will convert the string variable a to a number. Naturally, when using strings in mathematical operations you need to be certain that they actually contain a number or otherwise the conversion will fail.

a = "10"
b = 2
c = a / b     -- c equals 5

c = "ten" / 2 -- incorrect

If you hadn't realized it by now, coercion makes your life easier by relieving you from converting variables explicitly. However, it has some peculiarities that could easily lead to runtime bugs. Coercion will not work with comparison operators such as less than (<), greater than (>) and so on.

100 == "100"
-- equals false

100 == tonumber("100")
-- equals true

100 < "100"
-- incorrect

Initialization

Variables that have not been assigned a value are "uninitialized". They are "nil" by default and cannot be used in operations unless you give them some initial value. The expression a + 5 is invalid by itself because we haven't specified the value of a. Take a look at the following example. What is wrong with the expression a = a + 5? As you remember from the paragraph on operator associativity in our last chapter, the above statement actually means a = (a + 5). In other words, the right-hand side of the expression is evaluated first. At that moment, Lua will crash, since a was never assigned any value to begin with.

a          -- a is nil
a = a + 5  -- incorrect

Next: Conclusion