Game Development Reference
In-Depth Information
Boolean Math
Boolean math is an important tool in the developer's arsenal. If you understand and harness the
power of Boolean math, you can reduce the number of lines of code and also get results.
Let's have a look at the simplest example:
local function getTrueorFalse(thisCondition)
if thisCondition == true then
return true
else
return false
end
end
Although most developers write their code like this, there are unnecessary if .. then statements
that could be avoided. This function can be rewritten concisely as
local function getTrueOrFalse(thisCondition)
return thisCondition==true
end
You can see that it is reduced and has just one line instead. This can also be used in functions
where we might want to return true or false based on ranges. For example, say we want to write a
function isNumberGreaterThanTen :
local function isNumberGreaterThanTen(theNumber)
return theNumber>10
end
We can just evaluate the results directly instead of using an if .. then statement to return true or
false .
You might also want to know how to switch certain parts of code depending on a condition. The question
is a bit too wide for this discussion, but let's try to narrow it down to fit the context of this section.
One way to allow or disallow certain portions of code to run is with a series of if statements:
local flag=false
function do Something()
if flag==true then
-- Execute this portion only if the flag is true
end
-- this portion is executed irrespective of the flag
end
doSomething()
Similarly, you can also use flags to disable certain functions. Let's say that we call a function every
few seconds to update the player's location on an onscreen map. Before the map is fully loaded and
displayed, there would be no reason to display the information onscreen. Or, in another scenario,
there is a touch handler that handles touches or taps on the screen, but we might want to temporarily
 
Search WWH ::




Custom Search