Subscribe to GameFromScratch on YouTube Support GameFromScratch on Patreon

29. September 2012

As per this post, Moai 1.3 has been released.  If you have never heard of it, Moai is a cross platform, mobile focused, Lua based gameimage development library written in C++, that is open source and completely free.  A lot of focus was put into MOAISim.setTraceback to enable better error reporting.  The list of announced updates is as follows:


Added MD5 Hash Writer to compute a hash of a stream as it writes
Added Crittercism crash reporting for Lua stack traces, See samples/util/util-crash-report
Fixed network reachability initialization on iOS
Fixed input bug with multiple presses in one 'Frame'
Android - Fixed incorrect accelerometer data on tablets
Android - Added C-Ares ( Fixes DNS lookup blocking on HTTP calls )
Android -Added MOAILocationSensor
Android - Added MOAICompassSensor
Android - Fixed status bar issues with 3.1 tablets
iOS - Updated Facebook SDK to 3.0
iOS - Updated Crittercism SDK
MOAIApp - Added getUTCTime to Mobile
MOAILayer - Fixed bugs where MOAILayer:setVisible had no effect
MOAIHttpTask - Added 'getProgress' function to HTTPTask for Curl
MOAIJsonParser - Fix for issue with 64bit ints
MOAIFmodEx fixes for 'setLooping'


You can learn more about Moai right here or you can check out the tutorials on this very site.

News ,

27. September 2012


The author contacted me a few weeks up with a heads up that he had a Moai friendly Lua IDE in development and I said I would look into it… and well, I didn’t.  Things came up, then something else and something else and frankly it got pushed into the back of my mind.  In the end, that was a good thing too, as since that point in time the author has added auto-completion… a critical feature.


As of writing though, this feature is only available from the github sources.  So long as you have cygwin configured ( assuming you are working with Moai, you should already ), and git installed, the process is fairly simple:


cd /cygdrive/c/folder/to/install/to

git clone


This will create a folder ZeroBraneStudio with all the appropriate files. 

EDIT (29/09/2012): Author made update, should no longer need to set permissions described below

There is another catch, git mangles the executable permissions on Windows.  The long answer is well… long, the hackishly easy answer is to run:

chmod a+x –R ZeroBraneStudio


There is one last catch, you need to set the MOAI_BIN environment variable to point to your MOAI host folder, either that or add it to your PATH variable.  ( I suggest the former ).  To set the MOAI_BIN path, simply open a command prompt and type:

setx MOAI_BIN c:/path/to/moai/host


You can of course set the environment variables using the System control panel, but this will require you to reboot your computer for the change to take effect.  SetX simply requires you close the console to take effect.


Now you should be able to run the Studio, just double click zbstudio.exe to start it.  Hopefully the author will have a new release soon, that prevents all of this ( except the MOAI_BIN environment variable that is ).  Finally run ZeroBrane and this is what you see:





So then… why?  What does ZeroBraneStudio bring to the table that SublimeText or IntelliJ don’t have?


That’s an easy one.  I mentioned the first one earlier:




Auto-completion!  After years of using Visual Studio, this one is a gigantic must for me.  Granted as I covered earlier, IntelliJ can be configured to supported auto completion.  But ZeroBrane Studio has a massive head up on IntelliJ, watch this!




This you cannot do with IntelliJ, and it is a gigantic advantage.  But auto-completion isn’t the only thing ZB brings to the table, ZeroBrane Studio has the ability to debug running code!  You can set breakpoints, step in/over and out, set watches and do dynamic expression evaluations, pretty much most of what you expect to see in a debugger. Oddly enough, this needed a Windows Firewall exception.


To debug your code, select a line of text to set a breakpoint then hit F9 to create a breakpoint ( a red stop sign will appear in the margin ).  Then select Project->Start Debugging Server.  Then select Project->Start Debugging or hit F5 to run your code and voila:



Code execution stops at your breakpoint.  Use F10, Ctrl+F10 and Shift+F10 enable you to navigate through your code. You can hover your mouse over a variable to inspect it’s value.  You can also right-click a variable and create a watch window like this:


Unfortunately you can’t drill down into an individual Lua table, but hopefully this feature gets added soon!


Perhaps coolest of all, ZeroBrane Studio enables REPL interaction.  You can open the console and interact with your code directly:



As you can see, you can interact with your values in real time, and here are the results in the output:



It also has the ability to analyze your code, and show you the plethora of stupid mistakes you are making:



Not everything is perfect.  As mentioned earlier, watch expressions cant drill down into Lua tables, hopefully something that will change soon.  Additionally, it would be nice if the Moai host could be added using a configuration setting instead of using MOAI_BIN, as it makes it difficult to change between runtimes ( moai, moai-untz, release, debug, etc… ), but this is a minor point.  It would also be nice to be able to control more via context menu’s ( add breakpoint, step over/in, etc ). The code syntax highlighting could be improved a bit as well.  Of course, as a straight code editor, it isn’t going to give IntelliJ or SublimeText a run for it’s money just yet.



That said, this is an absolutely invaluable tool for people working with Moai or LOVE, the debugger and full auto-completion guarantee that this is going to be a stable part of my toolset going forward.  Hopefully the author is able to add more detailed debugging information soon.  If you are working in Moai or LOVE, you owe it to yourself to check out ZeroBrane Studio.


Speaking of which, you can get more information here.  Keep in mind, MOAI auto-completion is currently only available in the source distribution, at least as of version 0.32.  Hopefully the new release is bundled soon.



I have spoken with the author, and it appears a few of my issues aren’t issues after all.

The system will check for Moai executable in your PATH environment
variable. You can also set "path.moai = 'd:/lua/moai/moai'" in
cfg/user.lua (see cfg/user-sample.lua for example).



ZeroBrane actually can drill down details into a Lua table, in my relative Lua newbishness, I made a pair of mistakes.  First off, it only works on local variables.  Second, Moai does not return tables, it returns Userdata, which ZeroBrane currently can’t parse ( fingers crossed he figures out a way! ).




Here is the behaviour I was expecting to see, and exactly what I got once I defined the table as a local.

General, Programming , , ,

25. September 2012


Just last week I announced the release of Blender 2.64 RC 1, well it appears that 2.64 wasn’t quite ready for prime time, as there is now another release candidate.


Since this is a second release candidate, I assume there is no new functionality ( the release notes are shared with the last RC, so it is difficult to tell what has changed ), however the bug fixes list is rather large, so I assume this is largely a bug fix release. 


However, I don’t recall this portion being in the prior release notes, so perhaps it is new:

Mask Editor

Blender2.64 mask.png

Masks can now be created in the image and movie clip editor. They can be used in compositing to define areas of influence for nodes, block out unwanted objects, or help with green screen keying among other things. A mask datablock was added, consisting of splines that can be drawn and edited with the usual tools. Feathering can be controlled per spline point. Animation of these masks is possible with standard keyframing and drivers, but also by following motion tracks and parenting to other masks.



Regardless to what exactly has changed, if you are interested, you can download the release candidate from this page.  Or of course, you could just wait for the final release next week… but what fun is waiting??  I love new software releases, it’s like mini-Christmas!

Art, News

23. September 2012

This is one of those things I am constantly searching for, so I figured I might as well put something together so I end up on my own site!


The following is simply a list of devices and their respective screen resolutions.  I am writing this as much for me as anything else, but hopefully some of you find it useful too.


Device Name


PlayStation Portable (PSP) 480x272
PlayStation Vita 960x544
Nintendo DS  2 x 256x192
Nintendo 3DS 800x240 upper screen ( 400 per eye, effectively 400x240 ). 320x240 lower screen
iPhone 3 320x480
iPhone 4 640x960
iPhone 5 1136x640
iPad 1024x768
Galaxy S2 480x800
Galaxy S3 720x1280
Galaxy Note 800x1280
HTC OneX 720x1280
Lumia 920 768x1280
Lumia 820 480x800
Transformer Prime 1280x800
Razor HD 1280x800
Common Resolutions by name
QVGA 320x240
VGA 640x480
WVGA 800x480
XGA 1024x768
WXGA 1280x768
UXGA 1600x1200
WUXGA 1920x1280
Television Resolutions
Standard Def NTSC (480i) 720x480 interlaced
Standard Def PAL (576i) 720x576 interlaced
720p 1280x720
1080i 1920x1080 interlaced
1080p 1920x1080
4K 4096x1714 ( varies by manufacturer )

Design, General

21. September 2012


Alright, the title might be a bit over the top… what we are about to do is look at some of the most popular 2D game engines powered by Lua.  First there will be a matrix of features, to give you an “at a glance” view of what each engine offers.  Then we will follow up with a simple Hello World example for each, so you can see what the code would look like.  Hopefully this will help you decide which engine is right for you.


Engine Features Matrix








Site Link

Link Link Link Link


199$ /year iOS
199$ /year Android
349$ /year Both
Free trial available
149$ /year Indie
449$ /year Pro
0$ /year Community
Free Free

Free Limitations

Cannot publish to app store with free version Mandatory splash screen
Pro required if income greater than 100K$

Target Platforms

(Mac and Windows under development)
Linux (in late stage development)
Chrome NacL

Dev Platforms


Support Available

Paid support
Forum Forum Forum
Paid Support

Open Source

No No Yes Yes


Corona SDK Mobile Game Development

Learning Corona SDK (DVD)

Other Details

Builds occur on Corona Labs servers, internet connection required
3rd party tools available
Enterprise version available
Includes it’s own IDE Gideros Studio   Paid cloud computing offering for back-end services

Example Published Games

Go Ninja
The Lorax (Movie Game)
Joustin Beaver
Cerberus: The Puppy
Unpublished list
Crimson Steam Pirates
Strikefleet Omega


* Note, I gave iTunes link only, although many of those games are also available on Google Play.



Now we are going to look at a simple Hello World app written with each suite.  I do not pretend mastery of any of these suites, or Lua in general, so take the code for what it’s worth.  If you wish to submit a better rendition, please do so!


In this sample we are going to create a window at a resolution of 1280x800, then we are going to start a background song looping ( Richard Wagners – Ride of the Valkyrie taken from here ).  Then we are going to create a Hello World text/graphic centered to the screen, and position it where ever the user clicks/touches.  Some files handle window creation in a different file, some handle it in a single file.  That is why some versions have two lua files, while others have only one.


Corona SDK Hello World



-- config.lua

application =
    content =
        width = 1280,
        height = 800,
        scale = "letterbox"


-- HelloWorld sample

-- Load audio file
local song = audio.loadSound("../../Media/Ride_of_the_Valkyries.mp3")

-- set volume to 50%

-- play audio file, looping forever,{ channel=1,loops=-1})

-- create text to display on screen in 72point font
local helloText = display.newText("Hello World!",0,0,native.systemFont,72)

-- center to screen
helloText.x = display.contentWidth/2
helloText.y = display.contentHeight/2

-- red

-- function to handle touch event, move helloText to the touch location
function onTouchHandler(event)
    helloText.x = event.x
    helloText.y = event.y

-- register touch function to respond to global touch events






-- Helloworld sample

-- setup our window to our 1280x800 resolution

-- Load song, cannot use relative path to parent directory since file needs to be added to project
local song ="Ride_of_the_Valkyries.mp3")

-- play audio file, looping forever
local soundChannel = song:play(0,math.huge)

-- Set song volume to 50%, not set globally

-- need to load a ttf font, size cannot specify character size in TextField
local font ="arial.ttf",72,false)

-- create text to display on screen
local helloText =,"Hello World!")

-- center to screen
        application:getLogicalWidth()/2 - helloText:getWidth()/2,
        application:getLogicalHeight()/2 + helloText:getHeight()/2)

-- set text to red, color is hex encoding

-- display text

-- function to handle touch event, move helloText to the touch location
function onTouchHandler(event)
    helloText:setPosition(event.x - helloText:getWidth()/2,event.y + helloText:getHeight()/2)

-- register touch function to respond to global touch events
-- The above doesn't work in the simulator, so handle mouse too




function love.conf(t)
    t.screen.width = 1280
    t.screen.height = 800


-- love2d works slightly different, expecting users to implement methods that will be called within the game loop
-- such as love.draw() and love.update()

-- create a 72 point font using the system default
font =
-- set the font active
-- set red as the active color,0,0,255)

-- load audio file
local song ="Ride_of_the_Valkyries.ogg")

-- we want to loop, we want to loop, we want to loop, we want t^Z

-- set volume to 50%
-- play song

-- create a variable for print coordinates to update on touch, default to screen center
-- LOVE does not have a positionable text object, so we call print each frame
local x =
local y =
local stringWidth = font:getWidth("Hello World!")
local stringHeight =  font:getHeight("Hello World!")

-- This function is called once per frame to draw the screen
function love.draw()"Hello World!",x - stringWidth/2,y-stringHeight/2)

-- called on click, move our print x,y to the click location
-- no touch handler because LOVE is desktop only
function love.mousepressed(mouse_x,mouse_y,button)
        x = mouse_x
        y = mouse_y





-- create the window, viewport and layer
MOAISim.openWindow("Window", 1280, 800)
local viewport =

local layer =

-- Let Moai know we want this layer rendered

-- Initialize the audio system

-- set volume to 50%

-- load the song
song1 =

-- play audio file, looping forever

-- save memory by only rendering the chars we need
chars = 'Helo Wrd!'

-- create a font
local font =

-- create and position text centered
local helloText =
helloText:setString('Hello World!')


-- handle mouse/touch click events
function handleClickOrTouch(x,y)

if MOAIInputMgr.device.pointer then
    -- Mouse based device
            if(isButtonDown) then
    -- Touch based device
        function(eventType,idx, x, y, tapCount)
            if eventType == MOAITouchSenser.TOUCH_DOWN then




My Opinions



First off, take these with a grain of salt, these are just my initial impressions and nothing more.  Obviously it is all very subjective.  It is also stupid to say X is best, they are all good libraries, each with their own strengths and weaknesses.  I think that is perhaps the greatest surprise, not one of these four options is bad.



Love: Not a big fan of the abstraction and it forces a design on you, but this isn’t necessarily a bad thing, especially for a beginner.  Good for beginners, so-so to slight levels of documentation but absolutely wonderful reference materials.  Only library in this group with no mobile support, which is a big deal.  Open source and free, targeted to hobbyist.  Few ( none? ) commercial games.  All told, it reminded me a lot of the Python based PyGame, which is frankly a great beginners library.  Also the name “Love” proved a gigantic handicap, as it made Googling for anything beyond the Love2D website very difficult.  This is the downside to using a very generic name for your library ( cough… GamePlay, I’m looking at you! ).  The generic name really did prove to be a pain in the butt at times.  Love is certainly a good library, but probably not for professional use, at least, as is. 



Corona: Most polished of the four.  Best documentation, good API.  Only library with published books available and good tooling support.  Also most expensive and closed.  If it isn’t part of Corona, you are hosed.  Have to pay more for native access.  Great developer backing, lots of successful companies using Corona.  Corona is certainly a great library, although thanks to the price tag, it wont appropriate for all developers.  The lack of freedom ( no source, paying for native access ) are definitely the biggest drawbacks.



Gideros: Ok-good documentation, good reference but other material is a bit too scattered.  IDE is a HUGE boon for newer developers, especially with auto-completion.  That said, the IDE got a bit flaky at times too.  API itself a bit less intuitive ( to me ).  Licensing terms reasonable ( better than Corona, worse than Love and Moai ), same for price.  Good choice for beginner who wants to support mobile, lack of major published games a bit of a deterrent for professional developers, as is the lack of source code.



Moai: Moai is certainly the most difficult of the four, and the documentation is in heavy need of updating.  The reference itself is actually very good, where it exists.  In some cases there is none and in others, it is lacking or out-dated.  The developers are aware and this is a priority for them to fix.  On the other hand, Moai is also the most flexible by a mile.  The code ( as you can see from the example above ), is a bit more verbose, but that is because the library makes less decisions for you.  This is a double edged sword of flexibility vs ease, and Moai slants heavily towards flexibility.  Supports the most targets of all the libraries, has complete source code, and more importantly, the source code is very well written and very easy to read.  Like Corona, there are some very good shipped games.



Final verdict:

For a commercial product for iOS/Android, I would select Moai.  The API is a natural fit to my coding style ( I prefer flexibility over accessibility for time critical code ) and the C++ source code is a great boon to me, but to a non-C++ programmer, this would obviously be less important.  Also of course, the price is nice.  Most importantly, the open nature means I know I will never encounter a problem that I can’t code my way out of, the biggest downside to Corona.  If it wasn’t for the open source nature of Moai, I would probably go with Corona for the sake of it’s excellent documentation and clean API.


If I was just starting out, I would be torn between Gideros and LOVE.  LOVE is certainly the most beginner friendly, but the turn-key all in one nature of Gideros… you literally install, load the studio, write some code and hit play… with full autocomplete code editing.  This really is a huge deal!  In it’s favour over LOVE is also the support for mobile platforms.  That said, if the API isn’t to your liking, or you struggle with it, Love is easily the most accessible code wise.  I will be looking a bit closer at Gideros in the future.  Ran into a few annoyances during my brief exposure, like the inability to set anchor points for TextField values ( ), forcing me to wait for the feature to be added by someone else.


This isn’t to say Corona is bad, it obviously isn’t.  It is polished, has the best documentation and a very solid/natural API.  For me though, the lack of flexibility and access to source code provides outweigh it’s advantages.  If the source isn’t a big deal to you, or you do not have access to C++ resources and are willing to pay 200$ a year or more, Corona is a very good option with a ton of developers using it.  Also, Corona is the only option with a paid support option, which can be a huge advantage.




TL;DR verdict:


For a Pro developer:  Go Moai, unless you have no in-house C++ talent, in which case, go Corona.

For a new developer: Go Gideros, especially if you want to do mobile development. If you don’t like it, Love is always a great option.

Programming, Design, General , , ,

Month List

Popular Comments

Debugging 101 Tutorial or How to bring sanity to an insane world
Subscribe to GameFromScratch on YouTube Support GameFromScratch on Patreon

8. August 2014


I write a great many tutorials targeting newer developers and as a direct result I am exposed to a fair number of programming related questions.  I don’t mind in the least by the way, it’s why I run this site.


However, I notice one very common thread among those questions…


They often could have been solved with just a few minutes in the debugger.


Then it dawned on me.  Lots of newer programmers likely don’t know all that much about debugging.  Many are probably resorting to printing to the console to see how their program works.  For good reason too…  if you pick up say… a C++ book, it’s about the language, not the tooling.  Of course, there are dedicated books such as Beginning Visual C++ 2013 or the Eclipse IDE: Pocket Guide, but these tend not to be books beginners start with.  Hell, for someone just starting out, figuring out where the language begins and the IDE ends is challenging enough!


Which is all a shame, as basic debugging skills will make your life a hell of a lot easier.  Not only will it make solving problems much easier, but it will help a great deal in understanding how your language works.  Plus the most tragic part of all, it’s actually very simple and often incredibly consistent across tools and programming languages.


So, if you have no prior debugging experience, give me 20 minutes of your time.  I guarantee you it will be worthwhile, or your money back!



I am going to use a couple different languages/IDEs int this tutorial, but as you will see, the process is remarkably similar regardless to what language you use.  I am primarily going to start with Visual Studio, then illustrate how you can perform similar actions in other environments.  First a quick glossary of terms you are going to hear.



Glossary of terms


These are a few of the terms we are going to be covering during this tutorial.  Don’t worry over much if the following descriptions don’t make a lot of sense, it should be clearer by the time you finish.



This one is critical, these are instructions that tell your code HEY, STOP RUNNING, I WANT TO LOOK AT SOMETHING HERE!  We will be using breakpoints extensively.  You can generally add/remove/enable/disable breakpoints.



This one is incredibly well named.  Basically these are variables you’ve said you want to keep a watch on the value of.



Think of these like Watch expressions the IDE automatically made for you.  Basically every variable in local scope will be listed as a local.  Not all IDEs do this, but most do.


Expression Evaluation

This is powerful.  Basically you can type some code and see what result it returns, while your code is running.  Generally you do this once a breakpoint has been hit causing your code to pause and your debugger to be shown.


Call Stack

This is the hierarchy of function calls you are currently in.  For example, if you called myFunc() from main(), your callstack would look like




Don’t worry, this should make sense shortly.



C++ and Visual Studio Debugger


I am going to start with Visual Studio/Visual C++ then show other platforms later on.  Once again, most of the process you see here is applicable to other environments.


Let’s start with this ultra simple code example:

void someFunction(int & inValue)
    inValue = 43;

int main(int argc, char ** argv)
    int i = 42;
    return 0;


The code is extremely simple. We create a simple int, assign it a value, then pass it into a function that will assign it a different value. Now time to do some basic debugging.


The first thing you need to do is start debugging.  In Visual Studio, there are a couple ways to do this.  First thing, in C++, you need to tell it that you are building for debugging.  You see, when you make a debug build a few different things happen.  There are little bits of information added to your code that make the debugger work.  There are some other changes too, like memory being zeroed out, but those are beyond what we are talking about here.  The take away is, you need to build for debugging, then run the debugger, although generally this task is one and the same for you the developer. 


From the Visual Studio toolbar, you can do both:


Or, you can run from the Debug menu:



As you can see, F5 is also an option.  It’s worth noting, debug code generally runs a bit slower and bigger, so when you are finished development, you want to compile for release.


Ok, so that’s how we start the debugger, but in this code sample, it will simply start, run, then finish.  That’s not very exciting.



Enter the breakpoint!


Ok, now we are going to enter the wonderful world of breakpoints, your new best friends.  Let’s start by setting a breakpoint on our first line, where we declare i.  There are a number of ways of setting a breakpoint.  In the IDE you can right click the line of code you want to break on then select Breakpoint –> Insert Breakpoint, like so:



… for the sake of this tutorial, please just ignore Tracepoints, at least for now.


You can also set a breakpoint in the Debug menu, using Toggle Breakpoint, or by hitting F9:



The line of code you just set a breakpoint on should now have a red bullet in the margin:




Go ahead and press F5 to debug your program.  Things will go much differently this time, your code will stop executing on the line with the breakpoint.  You can hover your mouse over a variable to see it’s value:




In this case, you will see that the value is gibberish.  This is because i hasn’t been assigned yet.  Notice the little yellow arrow on the left hand side?  This is the line of code you are currently executing.



Stepping over the corpses of your vanquished foes



Now we need to navigate in the debugger.  This is done using a couple simple commands:




Step Into, Step Over and Step Out.  These are also available in the toolbar:


As you can see, you can also use the hotkey F11 and F10.  These keys change from program to program... if they didn’t, that would just make life too easy, wouldn’t it?


Now as to what these do…

Step Into, steps into the currently running line of code.  For example, if you are on a function, it will step into that function.  I will show this in a second.

Step Over jumps to the next line of code in the same scope.  Step out, jumps up on the callstack.  Again, I will explain this in a second. 


So what we want to do now is Step Over, and now it should look like this:



The little yellow arrow will now have advanced to the next line of code.  Notice now if we hover over the value of i, it is now 42 like we would have expected.  That is because the line of code has now executed.  This is a very important thing to realize… the line of code your breakpoint stopped on hasn’t executed yet.  So if you want to see what value is assigned to a variable, you generally want to set the breakpoint to the next line of code.


Now we want to “Step Into” the current line of code.  That is, we want to see what happens when someFunction() executes.  If we chose “Step Over”, we would jump to the next line ( return 0; ).  There is another important thing to realize here… even if you Step Over some code, it is still being run like normal, it just isn’t showing you it in the debugger.  That said, we want to see someFunction() in action, so choose Step Into or choose this icon:




Now the line of code jumps to the beginning of someFunction():




You can hover over parameters to see their value:



You can continue stepping in and over code like normal, or if you are done looking at someFunction ( or some other function someFunction calls ), you can choose Step Out to jump up on the callstack.





Callstack me, maybe?  No, I didn’t just make that pun did I?



Callstack… there’s that word again.  Now that we are actually in a bit of a call stack, let’s take a look at what I mean.


In Visual Studio, make sure the CallStack window is being shown.  This is controlled using Debug->Window->CallStack or CTRL + ALT + C like so:



A window like the following should appear:



The key to the name is “STACK”.  Think about it like a stack of plates at a cafeteria.  Each time a function is called, it’s like putting a plate on the stack.  The bottom most plate/function is the oldest, while the top most is the newest.  In this case, the call stack tells us that on line 9, in the function main, we called someFunction() and are currently running on line 2.  Speaking of “lines”, you have the option of toggling them on or off in Visual Studio ( and most other IDEs ).


The process of toggling line numbers on/off, isn’t incredibly straight forward.  That said, line numbers can be incredibly handy, so lets do it.  First select the menu Tools->Options…



Then in the resulting dialog on the left hand side scroll down until you find Text Editor->C/C++->General, then click the checkbox next to Line Numbers.  Obviously if you are using Visual Studio and a language other than C++, you need to pick the appropriate language:




Now line numbers will be displayed next to your code:



Ok… back to the callstack.  Double clicking an entry in the callstack brings you to that line of code.  In this trivial example, the utility is questionable.  However, when working with a real project, where the callstack might span multiple source files, it becomes a very quick and easy way to jump between source files and for seeing how you ended up where you are.  This obviously is a hell of a lot more useful when someFunction() is possible called from thousands of different locations for example.



Locals, no more witty titles after that last witless one…


Now let’s take a look at locals, a concept I mentioned earlier.  This is basically all the local ( non-global ) functions in the current scope.  While debugging inside someFunction, like so:




Open up the locals window.  Like before it can be toggled using the menu Debug->Windows->Locals:




Now you will have a new window, like so:




This is a list of all variables in the local scope.  Inside someFunction() there is only one value, it’s parameter inValue.  Here you can see that the current value is 42 and it’s data type is int reference.  As you step through someFunction, as values chance, they will be updated in the locals window. 


Step out of someFunction ( Shift + F11, or using the icon or menus listed above ), and you will see the locals change to those of main():





Now you see something somewhat unique to C and C++ ( and other languages with direct memory management ).  The value passed in, argv, is a pointer to a pointer of type char.  This is to say, it points to a pointer that points to the memory address of a char data type.  If that is greek to you at this point, don’t worry about it.  You will notice though that the locals window has done a couple very cool things.


First, you see a hex value:





This is the actual address of the pointer in memory.  After all, that is what pointers actually are, locations in memory.  This is incredibly useful in debugging, even if you yourself don’t use pointers, code you depend on might.  Look out for values like 0x0000000 or 0xFFFFFFFF.  If you look at the value of a pointer and it’s one of those values, your object wasn’t allocated or has been deleted.  These are some of the most common bugs you will find in C++ code.


The other neat thing that visual studio did was this:




The debugger was actually smart enough to go look at the data actually stored at the memory address this pointer points at.  Very handy.  You may also notice the triangle to the left of argv.  This is because there is more information available.  We will see this a bit more later.



Ok, now what?


So… what do you do once you have found what you were looking for?  You have a couple options.  Here they are from the debug toolbar:




Or using the following commands from the Debug menu:




One thing to keep in mind, when your programming is running, the options and menu’s available in Visual Studio are different.  For example, if you want to create a new project, you need to Stop Debugging before the menu options are even available.



Playing God with your Program


Ok, let’s rewind a bit and go back to the locals menu.  This time we are going to use a slightly different code example.


#include <iostream>
#include <string>

class MyClass{
    int myInt;
    std::string myString;

    MyClass() :
        myString("Hello World"), 

    int myPrivateInt;
int main(int argc, char** argv)
    MyClass myClass;
    std::cout << myClass.myString;
    return 0;


Now let’s try setting a breakpoint on the final line of main, like so:




If you run this code, you will see:




You will have to ALT+TAB over to it, since debugger has given focus to Visual Studio.


Now lets look at some of the funky things you can do to a running program.  Now let’s set another breakpoint, this one on the cout line.  Remember, the code on the line you’ve breakpointed hasn’t been run yet!




Now restart or debug your program again.  It will hit the first breakpoint right away.  Now go look at the locals window again:




As you can see, data types composed of other data types, like myClass can be expanded to show all the other values that compose it.  Now let’s do something kinda neat.


You can change the values of a program as it is running.  Sorta…  For basic data types, it’s extremely straight forward.  For example, to change the value of myInt while debugging, simply right click it in the locals window and select Edit Value, like so:




You can now change the value:




From this point on ( during this debug session ), that value is now 42.  Of course, if the value is changed in code, it will of course be updated.  This allows you to tweak values interactively and see how it will affect your program’s execution.


With objects however, it is slightly more complicated.  In the previous case, we edited myInt which is a member of myClass.  But we couldn’t simply edit MyClass directly, as the debugger has no idea how.  Therefore you can’t just right click myString and select edit.  The debugger simply doesn’t know how to edit this data type ( this isn’t true for non-C++ languages ).  You can however modify the values that make up the string, like so:




As you can see, myString is of type std::basic_string, which is composed of an array of character values that make up the string.  So we can edit the character values to say… lower case our string.




Once again, Visual Studio is smart enough to understand the datatype.  So we could either enter the value ‘w’ or the ascii code 119.  Now if you continue execution of your program it will automatically run to the next breakpoint.  And if you look at the output, you should see:




One very important thing to note here… all of these changes are temporary.  They only last as long as the current debugging session.  The next time you run your program, it will run like normal.



I’m sick of these damned breakpoints


In that last example, when we selected Continue, we jumped to the next breakpoint, like so:




As you add more and more breakpoints to your code, they can make stepping through it incredibly annoying.  So, what can we do about that?


Well the first thing we can do is disable it.  Right click the red dot and select Disable Breakpoint, or select the line and hit CTRL + F9




And the breakpoint will be disabled.  Now it will show up as a hollow circle:




This allows you to re-enable it later, but until you do, the debugger will completely ignore the breakpoint.  You can re-enable it the same way you disabled it.  Right clicking and selecting enable, or by hitting CTRL + F9.



You can also remove a breakpoint complete in a couple ways.  First you single left click the red dot, and it will be removed.  The F9 key will also toggle a breakpoint on and off completely.  You can also right click and select Delete Breakpoint ( see shot above ).


Sometimes you want to remove or disable/enable them all at once.  You can do this using the debug menu:



Breakpoints are your friend, learn to love them!


I’m Watching You!


Now we are going to look at two final concepts, watches and expressions.  Let’s start with watches.

Until this point, we’ve only been able to look at variables declared in the local scope.  That’s all well and good, but what happens when we want to watch a value declared in a different scope?  Don’t worry, the debugger’s got you covered!


Consider this simple code example and breakpoint:




At this point in execution, your locals will look like:



That said, stringInADifferentScope has already been declared and allocated… how would you look at this value?


Well, there are two ways.  As you may be able to guess from the preamble, they are watches and expressions.  A watch is a variable you are keeping an eye on, even if its not currently local.  You can set a watch while debugging code by right clicking the variable and selecting Add Watch:




Now you can look at watches in the watch window using the menu Debug->Windows->Watch->Watch 1 ( or CTRL+ALT+W then 1 ).  You can have up to 4 sets of Watch windows in Visual Studio.  Now you can inspect the value of watched variables at any time:



If you watch a variable that isn’t in scope, it tells you:




When the variable notInScope comes back in scope, it’s value can be retrieved by hitting the refresh icon.


The other option is Evaluate Expression, which is called QuickWatch in Visual Studio.  It’s an incredibly cool feature.  You can invoke QuickWatch while debugging by right clicking and selecting QuickWatch…  or by pressing Shift + F9.




This opens a dialog that allows you to enter whatever value you want into the Expression tab, then press Re-Evaluate and it will look up the value:




The Add Watch button allows you to add the selected Expression to the watch window we just saw.


The cool thing about this you can actually call some functions on your object and get the results:





On One Condition


Back to breakpoints for a second, then I am done I promise.

Consider the following code sample:




This is a very common bug scenario, but you really don’t want to run through the debugger 100K times do you?  Generally with these kinds of errors, its only the last couple of iterations you want to look at.  Fortunately we have something called a conditional breakpoint.  This, as the name suggests, will only break if a certain condition is met.


Add a breakpoint like normal.  Add it to the line inside of the loop.  Now right click the red dot and selection Condition…




Now you can set the condition you will break on.




The breakpoint icon will now have a white plus in it:




Next time you run the code, it will only trip when the condition is hit:




Unfortunately, in Visual Studio, conditional breakpoints can make your code ungodly slow, so only use them when absolutely required.  In other languages and IDEs, this isn’t always the case.  I honestly think this is a bug in Visual Studio, as the above code should not require several seconds to evaluate, even with the additional overhead. 



One of the keys to happiness is a bad memory


One other thing that can be incredibly useful, especially in C++ is to look at a location in memory.  This functionality isn’t always available, depending on the language you are using.  In Visual C++, it’s incredibly easy and useful.  In the previous example, we filled an array of char with 100K exclamation marks ( at least, once we remove the = sign from <= :) ).  Let’s say we wanted to look at memory for data.


In the Debug->Windows menu, select Memory->Memory 1



A window will open up like this:



That is showing what’s in memory, starting at the address 0x00287764.  What you want is the address of the variable data.  In the address box enter the value &data.  (For non-C++ programmers reading this, & is the address of operator, which returns the memory location of a variable ). 


Now you will see:




As you can see, data is located at 0x006D781C and is full of exclamation marks ( shown on the right ), which is represented by ascii character code 21 ( as shown on the left ).  Looking at memory can often help you find nasty bugs.



Debugging in other languages/IDEs


The instructions above were obviously C++ and Visual Studio related, but you will find other than the windows looking a bit different, some slightly different names and different hot keys, the process is almost identical.  Instead of going through the same process for every language, I will instead point out where all of these things are located or what they are called.




Java in Eclipse



Just like in Visual Studio, there is both a debug and run mode.  In order to debug in Eclipse you need to run using debug.  There is a menu option available:


You can also right click your project in the Package Explorer and select Debug As->Java Application.



Or using the Debug icon in the toolbar:



When you debug in Eclipse, you will be prompted to open in Debug perspective:



A perspective is simply a collection of windows and toolbars to accomplish a given task… such as debugging.  You can switch between perspectives using the top bar:


Or using the menu Window->Open Perspective.



Setting a Breakpoint:

You can set a breakpoint in a number of ways in Eclipse.  In a source window, you can right click the side column and select Toggle Breakpoint ( or CTRL+SHIFT+B ).  This adds a breakpoint, or removes on if there is one currently added.


You can also toggle a breakpoint using the Run menu:



Step Into/Step Over/Step Out:

While running in Debug perspective, you can perform stepping using the toolbar:


You can also resume and stop your program using this toolbar.  The icons are Step In, Stop Over and Step Out, from left to right.


You can also step using the Run Menu:


You can also use F5/F6/F7 to control stepping.


Watch Window

In Eclipse, Locals and Watch are in the same view, “Variables”. 



Variables should be available automatically when you launch into Debug perspective.  However you can also open It using the menu Window->Show View->Variables.  Or Alt+Shift+Q, then V.




Local Window:

See above.


Evaluate Expression:

Evaluate expression is called “Expressions” in Eclipse and is available using the same menu you used to open Variables.


Once again, you can dynamically execute code and see the results using Expressions.


Conditional Breakpoints

To set a conditional breakpoint in Eclipse, add a breakpoint like normal.  Then right click the dot and select Breakpoint Properties:


Then in the resulting dialog, check condition and enter your condition logic in the box below:




JavaScript in Chrome



In Chrome ( and other browsers, IE, Opera, Safari and Firefox are all very similar in functionality ), there is no such thing as debug or release, unless I suppose you count minified code.  Simply set a breakpoint in your JavaScript and refresh the page.  You will however have to open Developer Tools to be able to set a breakpoint.  Do this by clicking the Chrome menu button, selecting Tools->Developer Tools



Or as you can see above, press F12 or Ctrl + Shift + I.  Memorize that key combo, trust me…


Setting a Breakpoint:

To set a breakpoint, in the go to a source file:



Then in the source listing, right click on the left column and select Add Breakpoint:


… bet you can guess how to set a Conditional Breakpoint… ;)

You can also toggle a breakpoint using CTRL + B.


Step Into/Step Over/Step Out:

Step Over: F10

Step Into: F11

Step Out: Shift + F11


Or you can use the toolbar:




Watch Window

Window is located on the right hand side of the developer tools and is called Watch Expressions:



Expressions and Watches are combined into the same interface.  You can simply add a new one by clicking the + icon, then type code accordingly:



Local Window:

Called Scope Variables in Chrome.  Located in same area:



Evaluate Expression:

See watch above.


Conditional Breakpoints:

Just like adding a regular breakpoint, but instead choose Conditional Breakpoint.


Then type your conditional logic code:



WebStorm / JavaScript


Ok.. I’m just being lazy here.  I remember I already wrote an article about debugging in WebStorm… recycling is good, no? ;)


Debugging your app in WebStorm


It actually covers 100% of what we just talked about above, except of course the memory view, as it isn’t applicable.


Ok, Done talking now


As you can see, across tools the experience is very similar.  Some IDEs are worse ( Xcode… ), some are very limited ( Haxe in FlashDevelop ), but generally the process is almost always exactly the same.  Of course, I only looked at a couple IDEs but you will find the experience very consistent in several different IDEs.  It’s mostly a matter of learning a few new hotkeys and window locations.


One area that is massively different in command line debuggers, such as gdb.  You are still doing basically the same things, just no nice UI layer over top.  A discussion of gdb debugging is way beyond the scope of this document and there’s tons of information out there.  Heck, there are books written on the subject!


Hopefully that process was useful to you.  A while back I posted an example where the debugger saved my ass if you want to see this actual process in action.  Debugging should be a part of your development process, it will make your life a hell of a lot easier, and your hair a hell of a lot less white.


Let me know if that wasn’t very clear, this tutorial may actually require a step by step video companion to go along with it.  If so, please let me know.

Programming , , , ,

blog comments powered by Disqus

Month List

Popular Comments