Game Development Reference
In-Depth Information
Notice that we have a variable called hasKey , and at first, the value is set to false . With that, we call
the function openTreasureChest , and the functions prints Nothing happens . But when we call it again
after setting hasKey to true , it prints The treasure chest opens . This is the simplest example of a
flag. In a game, you could have many flags that might be used together to determine certain actions.
In some cases, you can also use a flag to prevent certain things from happening. For example, you
can have a flag that would prevent a function from running.
Using a flag to manage if some actions can be run or not, it is very simple:
onHold=false
function giveBlessings()
if onHold == true then return end
print("Bless you")
=true
onHold is false , so when the giveBlessings function is called, it prints Bless you .
onHold set to true , and the function simply returns and nothing
Let's consider a scenario where we need to get multiple items before we can go and slay a dragon.
These would include having armor, a sword, a steed, a shield, and some spells. These are five items.
To check for multiple items, we use the Boolean and and or operators. In Lua, they work in a short-
circuiting manner—in plain terms, this just means that they evaluate a condition only when required.
Assuming that the flags for our items are called item1 through to item5 , we can do the following:
if item1 and item2 and item3 and item4 and item5 then
print("The king blesses you on your journey to battle the dragon")
else
print("You are still not ready for battling the dragon")
end
This code works perfectly fine, but it can be made better. If the game had to report back to the
player on the number of items collected vs. the total number of items that were to be collected, we
would be left wondering how to achieve that. Here's one way to accomplish it:
local items={} -- Better to have an array for multiple items
local maxItems=5
-- Number of items required to be ready
function isPlayerReady(theItemsArray)
local count=0
local i
for i=1,maxItems do
 
Search WWH ::




Custom Search