Handy Code Snippets

This is a post that lists some handy code snippets. They will generally be small examples and the list will be added to in time and also if you guys post some snippets I will add them to this list.

Print/Display a boolean value preceded by a string

Problem :

If you try to simply print a boolean value preceded by a string like so :

local myBool = true
 
print("Value of my bool = " .. myBool)

Here's a lua implementation of C's ternary operator:

for those who do not know, in C

1
2
3
4
5
if a>10 
  b=a+1;
else
  b=a-1;
end

How to make a Health Bar

If you are new to corona and wandered how to implement health bar to your game( for certain object or enemy), here's my little code:

1
2
3
4
5
health_bar = display.newRect(0,0,200,10)
health_bar:setReferencePoint(display.TopLeftReferencePoint)
health_bar.x = 50; health_bar.y = 10
health_bar:setFillColor(0,255,0)
gameGroup:insert(health_bar)

May also be worth including the memory usage function here;

1
2
3
4
5
6
7
8
9
10
local function monitorMem(event)
     collectgarbage("collect")
     
   print( "\nMemUsage: " .. (collectgarbage("count")/1000) .. " MB")
   print("Texture Usage " .. system.getInfo( "textureMemoryUsed" ) / 1000000)
       
   return true
end
 
Runtime:addEventListener("enterFrame", monitorMem)

Everybody should know that the print function accepts comma separated values so you should never have to use the .. operator in a print function. This is much more efficient too because temporary strings don't have to be created and collected.

1
print("Value of my bool = ", myBool)

Wow Eric, I did not know that ever! Thanks for it!

"love the commas instead that crazy dots"

:-)

views:1650 update:2011/12/28 9:26:54
corona forums © 2003-2011