|
 |
|
Branching is a really simple concept. I bet I don't even have to explain it. Read this out loud:
if food == "cheese" then
print("What tasty food!")
end |
"If food equals cheese, then print "What tasty food!", end." This code will only print the string if it's given the right food - otherwise it'll do nothing. We use two equals signs to make it different to the = we use for assigning variables. Mixing the two up is a common mistake - make sure you don't fall in the trap!
We can also specify what to do if not given the right food, like so:
if food == "cheese" then
print("What tasty food!")
else
print("That food is horrible")
end |
Sometimes you'll have a series of options that you want to respond differently - perhaps different things for different foods. You can do this with elseif.
if food == "cheese" then
print("What tasty food!")
elseif food == "bread" then
print("Good for sandwiches!")
else
print("That food is horrible")
end |
Other Kinds of Comparison
We've already seen == in action, but there are many other kinds of comparison. The opposite of == is ~=, which simply means "not equal to".
print(12 ~= 7)
print(6 ~= 6)
true
false |
You can also use less than <, greater than >, less than or equal to <= and greater than or equal to >=. They work like you'd expect:
print (5 < 7)
print (12 > 7)
print(7 >= 7)
print(7<=6)
true
true
true
false |
You can compare strings as well. Equal and not equal work how you'd expect. The other ones use alphabetical order:
print("cheese" < "haddock")
true |
All these operators are case sensitive, which is especially important with the less than and greater than symbols. The computer alphabet doesn't run AaBbCcDd like you'd expect - all capital letters come first, followed by all lower-case letters. So "Xylophone" < "bee" is true. If you want to ignore this case sensitivity, use string.lower or upper on the strings before you compare them.
name=zs.func.prompt()
if string.lower(name)=="fang" then
print("What an awesome name you have!")
end
What is your name? FANG
What an awesome name you have! |
Try creating some if...then...end commands of your own using what you've just learnt. Try mixing in some of the string. and math. functions we've already covered.
Also, a quick note on style. Sometimes it can get a bit confusing remembering where to put all the elses and ends, especially if you have ifs inside other ifs. You might find it works better if you fill out the whole if command first, like this:
if food=="cheese" then
else
end |
and then fill in the gaps with comments to help remind you what goes in each section.
if food=="cheese" then
-- say what a tasty food it is
else
-- say how horrible it is
end |
Anything after the two dashes -- will be ignored by Lua until it reaches the end of the line. If you're using an editor with syntax colouring, the comment will be a different colour. Some people use lots and lots of comments and some people use hardly any. It's up to you what you think makes code easier to understand, so use as many or as few as you like.
Expressions
These comparisons aren't giving us strings "true" and "false", they're giving us the objects true and false. The part between the if and the then is called an expression, and when Lua tests an expression it gives the result true or false. If the result of the expression isn't false or nil (remember nil? It's "nothing" - the value variables have when you haven't given them a real value yet) then the if will run the part before the else - if it's false or nil, it'll run the else part.
This means that you can test to see if a variable is defined very simply:
var=nil
if var then
print("Var has a value")
else
print("Var doesn't have a value")
end
Var doesn't have a value |
Of course, if the value of var is false, this will claim that it doesn't have a value. But since you almost never store false in variables, it probably won't be a problem.
Logic
We already saw how we can check things one after the other with elseif:
if food == "cheese" then
print("What tasty food!")
elseif food == "bread" then
print("Good for sandwiches!")
else
print("That food is horrible")
end |
Now imagine that we have two sets of items - tasty ones, and horrible ones - and we want to respond to each set differently. We could check for each tasty item individually, like we did in the previous example:
if food == "cheese" then
print("What tasty food!")
elseif food == "bread" then
print("What tasty food!")
else
print("That food is horrible")
end |
But this is a pretty ugly way of doing it. The most important piece of programming advice I was ever given was Don't Repeat Yourself (also known as the DRY rule). If you take nothing else away from this tutorial, take that - be lazy. Try to solve problems by typing as little as you can.
Here, we're repeating the line print("What tasty food!"). Why is this such a problem? Well, what if I'd made a mistake and then copied and pasted that mistake all over my script? What if I wanted to change the output to something else (Like "Wow, I love " .. food .. "!")? I'm lazy, I don't want to have to rummage through my whole script fixing line after line.
if food=="cheese" or food=="bread" then
print("What a tasty food!")
else
print("That food is horrible")
end |
Much simpler. I used the or operator to get them to work. There's also and and not. Here they are in action:
iAmFang = true
iAmAGuru = true
iAmFemale = false
iHateLua = false
print(iAmFang and iAmAGuru)
print(iAmFemale and iAmAGuru)
print(iHateLua and iAmFemale)
print(iAmAGuru and iHateLua)
print("")
print(iAmFang or iAmAGuru)
print(iAmFemale or iAmAGuru)
print(iHateLua or iAmFemale)
print(iAmFemale or iAmFang)
print("")
print(not iAmFang)
print(not iAmFemale)
true
false
false
false
true
true
false
true
false
true |
or is true if either (or both) of the sides are true. and is true only if both are. not swaps the value.
Tim Toady
The and and or operators need a bit more discussion. Unlike all the other operators we just learnt about, they don't actually return false or true. or checks the part before the or first - if it's nil (or false), then it returns the part after the or; if it's not, it returns the part before. and is the opposite - if the first part is nil then it returns it, otherwise it returns the second part.
This might seem a bit weird, but if you think about it, it does make sense. If the first part of the and is nil or false, then the and has already failed - it should return false. If it's not nil, then if the second part is false or nil, it should return false, else it should return true (and since anything that isn't nil or false is true, returning the value is the same thing). This works in reverse for or.
This might take a few readthroughs and a bit of thinking to understand totally, but it does let you do some really nifty things I'll touch on in chapter 8's Tim section. |
|