Booleans and Types
Besides numbers and texts, Lua has one more simple kind of value: a boolean (named after the mathematician George Boole). It has only two values, true and false. It's the answer to a yes-or-no question: is it raining? Is the barn open?
local isRaining = false
local barnOpen = true
print(isRaining)
print("Barn open:", barnOpen)This prints:
false
Barn open: trueIn the next lesson, booleans will decide what your program does, for example whether Emma waters the field. For now, watch out for three things:
trueandfalseare keywords, so they're written without quotes."true"in quotes is a text that only looks like a boolean.- They're written in lowercase.
Truewith a capital letter is just a name, and since there's no variable calledTrue, its value isnil. - Like
nil, a boolean can't be joined to a text with..:"Raining: " .. isRainingends with the errorattempt to concatenate a boolean value (local 'isRaining'). Print it with a comma, or turn it into a text first, as you'll learn in the next exercise.
Every value has a type: a number, a text, a boolean… The function type tells you which one, as a text:
print(type(120))
print(type(2.5))
print(type("Emma"))
print(type(true))
print(type(nil))This prints:
number
number
string
boolean
niltype says number for integers and floats alike; to tell them apart, use math.type. Later in the course, you'll meet more types, such as table and function (try print(type(print))).
In Lua, the type belongs to the value, not to the variable. The same variable can hold a number now and a text later:
local harvest = 12
print(type(harvest))
harvest = "twelve"
print(type(harvest))This prints:
number
stringLua allows it, but it confuses anyone who reads the program. Keep one kind of value in each variable.
Instructions
Below, print milk and its type the same way as the two lines above:
Emma string
1 number
6.5 numberPrint barnOpen and its type the same way. It says string: the value is in quotes, so it's a text. Fix line 5 so that barnOpen is a boolean and the program prints:
Emma string
1 number
6.5 number
false booleanBoth cows and milk are numbers. On the last line, print what kind of number each of them is: math.type(cows) and math.type(milk), separated by a comma:
Emma string
1 number
6.5 number
false boolean
integer floatStart programming for free
7/10