An explanation of flags, what they are and how to use them in your apps.
Spending time in the New Users section of the Corona forums I have frequently found myself and others suggesting, “Just use a flag!” – which is often met with the online equivalent of a blank stare.
The purpose of this post is to give a brief explanation of flags as well as a simple example of how they might be used to better help your understanding of the process.
What Are Flags?
Flags can be used to tell us if the sound is on or off, if the user is touching the screen or not, if the hero in our game is on the right side of the screen or the left.
The sound on/off scenario is one of the more common circumstances in which we all find ourselves as we delve into app development and so my example will use this situation.
A Simple Flag (Plug and Play)
local bg = display.newRect( 0, 0, 320, 480 )
local sound = true
local function soundSwitch ()
sound = not sound
The above sample switches our variable (sound) between true and false when you tap on the background and prints the current value.
Why use flags?
Using the above example you could easily check whether sound was true or false during game play and accordingly.
Being able to quickly use
if sound == true
in a function whenever you need it is very useful.
You may also use a flag to check when a player is in a certain position on the screen – perhaps on the ground – and say if onGround == true then jump when the jump button is pressed, else do nothing. (To avoid being able to jump again in midair, etc.)
And that’s it!
Although this just scratches the surface of what flags can do I hope it will encourage new users to experiment with them – they are a simple but vital part of developing an application.