Create a calculator with Corona P.3

Make sure to visit the first two parts of this tutorial.
Part 1
Part 2

Its time to add some math logic, or a “calculator brain” to the app.
Create a new file in the same folder and name it ‘calcController.lua’. This class controls all the math functions of the calculator, such as add, divide, subtract, multiply, or any more complicated functions that you’d like to add later on your on.
[Read more…]

Create a calculator with Corona – P.2

Visit the first part of this tutorial.

In this part we will:

  • Make the buttons functional.
  • Create the calculator’s display screen.

Lets jump right into it and make these buttons do something!

Adding button functionality

When the user taps a button, such as the number ‘7’, the app should do something in response. For example, print the number ‘7’ on the screen. That’s the job of an event listener function, which is triggered by an event, such as a ‘tap’, and does something in response.

For the purpose of event handling, I decided to classify our buttons into three groups: number buttons, math buttons and the decimal button. So, we’ll need three different event listeners:

  • mathBtnTapped (event) – deals with math buttons (‘+’,’-‘,’/’,’X’,’=’,’+/-‘ etc) tap events.
  • numBtnTapped (event) –  deals with number buttons (‘0’-‘9’) tap events.
  • decimalBtnTapped (event) –  deals with the decimal (‘.’) button tap events.

To create them, add the following code right in the beginning of ‘main.lua’:

-------------------------------------------
--Button Handlers
-------------------------------------------
local function mathBtnTapped(event)
--handles the math buttons ("/","*","+,"-" etc)
	local targetID = event.target.id;
	print("You pressed "..targetID);
	return true;
end

local function numBtnTapped(event)
--handles the number buttons ('0'-'9')
	local targetID = event.target.id;
	print("You pressed "..targetID);
	return true;
end

local function decimalBtnTapped(event)
--handles the decimal button ('.')
	local targetID = event.target.id;
	print("You pressed "..targetID);
	return true;
end

At the moment, the only thing these event handlers can do is print out the ‘id’ attribute of the tapped button into the Corona Terminal.

We will make the buttons functional by assigning them the event handlers we just created.
Go to the ‘for’ loop, where we added the ‘id’ attribute to the number and decimal buttons. Locate the line:

btns[#btns].id = ".";

Below it, add the following line to assign the appropriate event listener, ‘decimalBtnTapped’, to the decimal button:

btns[#btns]:addEventListener("tap",decimalBtnTapped);

About three lines below it, locate the code:

btns[#btns].id = i;

right below it, assign the event listener, ‘numBtnTapped’, to the number buttons:

btns[#btns]:addEventListener("tap",numBtnTapped);

Finally, locate the line where we created the math buttons:

btns[#btns + 1] = btnClass.newMathFuncBtn(btnParams);

and assign its event listener, ‘mathBtnTapped’:

btns[#btns]:addEventListener("tap",mathBtnTapped);

Now run the app and see what happens when you tap the buttons.
Although nothing will change on the screen, if you check the terminal window, you’ll see a printout of the buttons pressed. Such as:

For now, lets leave it at that. We’ll return to the buttons and add more meaningful functionality to them after we create the calculator’s display screen.

The calculator screen

Under the same folder where your other files are located, create a new text file and name it ‘calcScreen.lua’. This file will hold the calculator display screen class. This new class would do two things:

  1. Create a new calculator display screen.
  2. Set its label to a given string.

In ‘calcScreen.lua’, type the following code and review the comments:

local class = {};
--this class creates the calc. display

	function class.new()
	--constructor class to create a new calc display
		--define a few variables
		local width, height, textSize;
		width = display.contentWidth-20;
		height = 40;
		textSize = 20;

		--a display group to hold our calc display
		local screenGroup = display.newGroup();

		--draw the background
		local bg = display.newRect(0, 0, width, height);
		bg:setFillColor(20,20,20);
		bg:setStrokeColor(255,255,255);
		bg.strokeWidth = 1;
		--position it
		bg:setReferencePoint(display.CenterReferencePoint);
		bg.x, bg.y = 0, 0;

		--create the text object
		local txt = display.newText("0", 0, 0, native.systemFont, textSize)
		txt:setTextColor(0,255,0);

		--position the label (we define it in a function
		--since we have to reposition the text every time
		--it's changed)
		local function positionLabel()
			local padding = 5;
			txt:setReferencePoint(display.CenterReferencePoint);
			txt.x = (bg.contentWidth - txt.contentWidth) *.5 - padding;
			txt.y = 0;
		end
		positionLabel();

		--insert the components into the main display group
		screenGroup:insert(bg);
		screenGroup:insert(txt);

		--public class functions
		function screenGroup.setTxt(str)
			txt.text = str;
			positionLabel();
		end

		--return a handle to our display object
		return screenGroup;
	end
return class;

The class.new() function creates a new calculator screen object. The screenGroup.setTxt(str) sets the displayed text to a given string. Note how the setTxt(str) function is a member of screenGroup. This allows us to treat this function as a “public” function, accessible from outside the class. In a moment, you’ll see how to call it through an instance of this class from within ‘main.lua’.

Now that we defined a class that creates a calculator display, it’s time to implement and test it. Why not test it with the buttons?

At the beginning of ‘main.lua’ add the following code:

-------------------------------------------
--The calculator display screen
-------------------------------------------
--require the external 'class' we created
local calcScreen = require "calcScreen";

--create a new instance of the calc. screen
local calcScr = calcScreen.new();

--position the newly created calc. screen
calcScr:setReferencePoint(display.CenterReferencePoint);
calcScr.x = display.contentWidth *.5;
calcScr.y = 50;

Now when you run the app you’ll see the calculator screen displayed above the buttons.

We first require the class so we can use the functions defined within it. Then, we create a new calculator screen object and pass it into the local variable ‘calcStr’.

In the numBtnTapped(event) function, add the following line just under or above the ‘print’ command: (we’ll remove this line later, this step is only for testing the setTxt(str) function)

calcScr.setTxt(targetID);

After adding this line of code run the app again. Now tapping a number button should set the display to the same number.

But we still don’t have a calculator behavior!

In the next part we’ll add the math logic and complete our calculator app.

Make sure to remove the last added line of code (calcScr.setTxt(targetID);) before proceeding to the next part. (again, it was only used for testing).

Create a calculator with Corona – P.1

In this multi-part tutorial, I’ll show you how to build a simple math calculator using the Corona SDK.

Part 1 – Creating the buttons

What you’ll need to begin:

  • The Corona SDK downloaded and installed.
  • Basic Lua language and Corona SDK knowledge. (go through the excellent tutorials at Ansca’s website).
  • A text editor.

First, we’ll create the calculator’s buttons. For a more modular and neater code structure I decided to write an external class that handles the creation of those buttons.
Although Lua doesn’t technically have classes, we can get a class-like functionality using tables and functions. You can find out more about this here, or simply follow my example below.
[Read more…]

Progress of my (still unnamed) aviation weather app

My newest app, an aviation weather app for pilots, is starting to take shape. It doesn’t have a name yet and took me almost 6 months to get to this stage, but I’m hoping to finish it soon.

There are plenty of weather apps in the app store, so a big question that pops up is: why get into such a crowded niche?
[Read more…]

Setting up Android hardware keys with Corona SDK

Supporting the Android hardware keys is essential for a good user experience. If you don’t support them in your app, you are almost guaranteed to get angry users——and bad reviews.

[Read more…]