Boo - lean

I am not trying to scare any persons that are thin, Booleans are a datatype that are commonly used in a programming language to denote a flag, a True/False or a On/Off type information. Now the question is how can one use this? or if you think that you have a perfectly good idea on how to use it, well, have a read and see...

The boolean is the easiest and yet the most underused datatype used by new developers. Even if it used on and off (no puns intended) it is not used properly or the power of these are not really understood.

So let's look at the common usages

Scenario #1
 local isOn = false

 if isOn == true then
   print("The switch is On")
   print("The switch is Off")

This does not do much, but demonstrates how a boolean is used for conditional statements.

Scenario #2

Here is a sample loop that runs from 1 to 10 using a while loop
 local i=1
 while i<10 do
  print("i = " .. i)
What if in this scenario, we had no idea of where the loop starts and when the loop ends, if that information was dependent on some other function? We could use this
 local isOn = true

 local function resultFromAnotherFunction()
  local j = math.random(1,100)
  if i % 2 ==0 then
    return true,i
    return false,i

 while isOn do
  isOn,i = resultFromAnotherFunction()
  print("i = " .. i)
In this example we got the value of should we continue the loop or not from a function. Scenario #3, We shall look at a boolean as a real switch
 local isOn = true

 local function printTenNumbers()
  if isOn == false then print("This function is disabled") return end

  local i
  for i = 1, 10 do
   print("Number " .. i)

 isOn = false
Hope that these three scenarios have demonstrated how booleans can be used, for all those that have a question on how can a particular function be switched on or off (normally the parlance or the word would be enabled / disabled) but that would be scenario #3. Use it for touches, in this way
 local function onTouch(event)
  if isIgnoreTouches then return end
   -- do the rest of the handling

hope this has helped,




Popular Posts