Short circuit evaluation (lazy operator) in Lua
Archive - Originally posted on "The Horse's Mouth" - 2008-06-22 00:42:39 - Graham EllisIn Lua, if a partial expression evaluates to true the following section will NOT be evaluated if it follows an or because the whole thing cannot be true.
If a partial expression evaluates to false, the following section will NOT be evaluated if it follow an and because the whole thing must be true.
If you find this a bit theoretic, try a real life example ...
If you're going to buy a kebab OR Fish and Chips and you find the kebab shop open, you won't bother to carry on up the road to the chippy because you have already met your needs.
If you require a hammer AND nails, but you can't find a hammer, you won't go and search for the nails because even if you find them, they're not going to be much use to you!
Let's see some code ...
function agelimit(incoming)
return type(incoming) == "number" and incoming or 18
end
-- And the code to call that function ...
print (agelimit(10))
print (agelimit(12))
print (agelimit("fourteen"))
print (agelimit(16))
And when you run that, you get ...
[trainee@easterton u106]$ lua lazy
10
12
18
16
[trainee@easterton u106]$
If you're wanting to learn to program in Lua and you're looking for a training course, please ask us (email info@wellho.net). Although we're not [yet?] offering a scheduled public course, we are running private courses for two different groups:
• Delegates with no prior programming experience
• Delegates who have programming experience, but are new to Lua.
Course can be run for groups of 3 to 10 delegates, and vary in length from 2 to 4 days depending on the background of the delegates, the size of the class, and just how deep you want us to go into certain aspects.
Some sample quotations:
• At our training centre - Melksham, Wiltshire, England
• At your office in the UK - example - Coventry, England
• At your office in the Ireland - example - Dublin
• At your office in the USA - example - New York State