Fleminger Mediahttp://www.flemingermedia.com
Indie Mobile App DevelopmentSun, 03 Feb 2013 23:28:20 +0000en-UShourly1https://wordpress.org/?v=4.4.10Create a calculator with Corona P.3http://feedproxy.google.com/~r/FlemingerMedia/~3/hZDAwN8Nsh0/
http://www.flemingermedia.com/2012/04/02/create-a-calculator-with-corona-p-3/#commentsMon, 02 Apr 2012 03:41:10 +0000http://www.flemingermedia.com/?p=207Make 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, […]

]]>Make sure to visit the first two parts of this tutorial.Part 1Part 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.

Basic operating principle

Our calculator stores up to two numbers, called operands, entered by the user, and performs a math operation on them when a math button or the equal buttons are pressed. The result of the operation is stored in operand1.

Here’s an example: The user inputs 56.4 + 100. Operand1 is 56.4, operand2 is 100. The result of the operation, 156.4, is stored as the new value of operand1 and displayed on the calculator’s readout screen. Next the user hits “X” and 10, the number “10” is inserted into operand2 and a multiply operation is performed between the two operands, resulting in 1564, which is now the new value of operand1.

For number input, we have to differentiate between two modes. The first is when a user starts entering a new number. This happens after the clear button or a math function button was pressed. When this occurs, the calculator clears the screen, adds the digit to the readout string and then displays it. If the last key pressed (stored in var ‘lastInput’) was a digit or the decimal key, that means that the user is currently typing a number. Therefore every digit pressed at this mode would be added to the right side of the readout string.

Lets get to work. At the beginning of ‘main.lua’ add the following variables and flags:

In order to put everything together, you’ll have to add some code to the the button tap listener functions we created in the previous part of the tutorial.
Here are the modified event listeners:

local function invertNegBtnTapped(event)
--handles the +/- event
local num = tonumber(displayStr);
--if num is not nil and is smaller then 0
if num and num<0 then
--remove the "-" (first char of the string)
displayStr = string.sub(displayStr,2);
--if num is not nil and is larger then 0
elseif num and num>0 then
--add a "-"
displayStr = "-"..displayStr;
end
--show the modified num on screen
if num then calcScr.setTxt(displayStr); end
return true;
end
local function mathBtnTapped(event)
--handles the math buttons ("/","*","+,"-" etc)
local targetID = event.target.id;
if targetID == "-" and startNewNumber then
negPressedLast = true;
else
negPressedLast = false;
end
--if this is not the first time in a row the '='
--button was pressed, dont change op2
--Example: the user enters "3+5 = = =" result is 18
if lastInput ~= "equal" then
cc.setOp2(tonumber(displayStr));
end
if targetID ~= "=" and lastInput=="equal" then
--treat the last result as it was a num entered by user
cc.setOp1(tonumber(displayStr));
cc.setOp2(0);
else
cc.performOperation();
end
displayStr = cc.getOp1();
if targetID == "=" then
lastInput = "equal"
else
lastInput = "math"
end
--set the typed math function (X, /, -, +) as the last operator
cc.setOperator(targetID);
--check for errors found by the calculator controller
--such as a divide by zero
if cc.foundError then displayStr = "ERROR"; end
--deal with the clear button
if targetID =="Clear" then
clear();
end
--show operand1 on the readout screen
calcScr.setTxt(displayStr);
return true
end
local function numBtnTapped(event)
--handles the number buttons ('0'-'9')
local targetID = event.target.id;
print("You pressed "..targetID);
--reset the readout string, if this is a new digit sequence to enter
--if lastinput was "equal" we are starting a completely new
--sequence of calculations, so we call clear()
if lastInput == "equal" then
clear();
elseif lastInput ~= "num" then
displayStr = "0";
decimalPressed = false;
end
--don't allow display longer then 'maxDigits'
if (string.len(displayStr) < maxDigits) then
displayStr = displayStr .. targetID;
end
--check if the "-" button was pressed before this number
if negPressedLast then
displayStr = "-"..displayStr;
negPressedLast = false;
end
--flag that the last button was a number button
lastInput = "num";
--clean '0' on left side of the readout string
displayStr = cleanLeftZeros(displayStr);
calcScr.setTxt(displayStr);
startNewNumber = false;
return true
end
local function decimalBtnTapped(event)
--handles the decimal button ('.')
local targetID = event.target.id;
print("You pressed "..targetID);
--reset the readout string, if this is a new digit sequence to enter
--if lastinput was "equal" we are starting a completely new
--sequence of calculations, so we call clear()
if lastInput == "equal" then
clear();
elseif lastInput ~= "num" then
displayStr = "0";
decimalPressed = false;
end
if not decimalPressed and (string.len(displayStr) < maxDigits) then
displayStr = displayStr..".";
decimalPressed = true;
lastInput = "num";
end
calcScr.setTxt(displayStr);
return true;
end

Note that I added a separate event listener for the ‘invertNegative’ button. This listener wasn’t introduced in the previous part for simplicity.

These are the highlights of the code. You can get the entire project here:SimpleCalc.zip

Let me know if you have any comments, questions, or suggestions for improvement.

]]>http://www.flemingermedia.com/2012/04/02/create-a-calculator-with-corona-p-3/feed/2http://www.flemingermedia.com/2012/04/02/create-a-calculator-with-corona-p-3/Create a calculator with Corona – P.2http://feedproxy.google.com/~r/FlemingerMedia/~3/10Lm6B4Gyhs/
http://www.flemingermedia.com/2012/03/20/create-a-calculator-with-corona-p-2/#commentsTue, 20 Mar 2012 18:35:25 +0000http://www.flemingermedia.com/?p=158Visit 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, […]

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:

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:

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?

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).

Part 1 – Creating the buttons

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.
Create a new text file and name it “buttons.lua”. This will be our buttons class.

Create another file and name it “main.lua”. This is the main program file. To test our button class, we will first require the external file, then create a temporary variable in main.lua to test it.
So, in “main.lua”, write:

Now, run the code in the Corona Simulator.
The Corona Simulator should load, but the screen is blank! However, if you look at the terminal display window, you should see a message “creating a new button”. This is the message we printed within the newBtn() function.

To get the button showing up on the screen, we’ll have to create some graphical elements first. The button will consist of a rounded rectangle as the background and a text object as its label.
But, before we get there, lets set up a way to pass arguments that make the button customizable. This way we can set up different background colors, width and heights and, most importantly, different label texts when we create a new button.

In “buttons.lua”, change the line reading:

function class.newBtn()

to:

function class.newBtn(params)

For now, params will be a table that can hold the following button variables:

labelTxt – a string with the button’s label text

bgColor – background color.

txtColor – the label color.

width

height

Next, review the full newBtn() function with the comments I made in the text:

Run the code in the simulator, you should see a little button with the label ‘5’ in the center of the screen.

Great! Now we just have to create the number buttons and the math function buttons. I wanted the different kinds of buttons to look slightly different from each other. This is a good opportunity to demonstrate how to implement simple inheritance behavior in Lua.

Specifically, we need to main groups of buttons for now: numerical buttons, and math buttons.

In “buttons.lua”, add the following functions just before the return class; line:

The first function, newNumBtn(), creates a numerical button (which we will use for 0-9 and the decimal buttons), the second one creates a math function button (for “X,”-“,”+”,”=”, etc). Note that these functions simply define new parameters and than call our more generic newBtn() function, we created earlier.

Before we write the code to show all of the calculator’s buttons, lets make sure that our new button constructors work. Change “main.lua” to contin the following code:

I inserted all the buttons into a table, that acts like an array, called ‘btns’. Each ‘btns’ member is a display group, and can hold its own variables or tables.
The ‘id’ member, added to each button in the btns table, will help us later identify what button the user tapped, when we code the calculator key events.
You should now have a completed calculator keypad on the screen. Unfortunately, these buttons still don’t do anything. That’s coming up in the next part of the tutorial.
Please let me know if you have any comments or questions!

]]>http://www.flemingermedia.com/2012/03/14/create-a-calculator-with-corona-p-1/feed/10http://www.flemingermedia.com/2012/03/14/create-a-calculator-with-corona-p-1/Progress of my (still unnamed) aviation weather apphttp://feedproxy.google.com/~r/FlemingerMedia/~3/kzeVMUnNA5Q/
http://www.flemingermedia.com/2012/03/01/progress-of-my-still-unnamed-aviation-weather-app/#respondThu, 01 Mar 2012 17:05:44 +0000http://www.flemingermedia.com/?p=103My 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 […]

]]>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?

Strong demand: Weather is one of the most popular app categories for pilots.

Personal angle: I’m an airline pilot, so I’m building an app that I’d want to use every day. If the app works for me as a user it might be just as helpful to other people in similar situations.

Fill a void: Some of the available apps are really great, and their developers did a tremendous job creating them. That said, there is always room for improved or new features offered by a new product in the market. (It’s the eternal question “There are so many cookbooks, why write another one?”).

]]>http://www.flemingermedia.com/2012/03/01/progress-of-my-still-unnamed-aviation-weather-app/feed/0http://www.flemingermedia.com/2012/03/01/progress-of-my-still-unnamed-aviation-weather-app/Setting up Android hardware keys with Corona SDKhttp://feedproxy.google.com/~r/FlemingerMedia/~3/p8MJwD4Wfng/
http://www.flemingermedia.com/2012/02/18/setting-up-android-hardware-keys-with-corona-sdk/#commentsSat, 18 Feb 2012 18:34:21 +0000http://www.flemingermedia.com/?p=56Supporting 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. Unlike the iPhone that only has one “Home” key, which can do many tasks and is completely handled by the operating system, Android devices have […]

]]>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.

Unlike the iPhone that only has one “Home” key, which can do many tasks and is completely handled by the operating system, Android devices have 4 different hardware buttons used for navigating the screens: Home, Back, Menu, and Search. Note that although it’s becoming more and more common to see these buttons as icons on a touchscreen, for the sake of simplicity we will still refer to them as “hardware keys.” The new Android release, Ice Cream Sandwich, changes this, as the hardware buttons will officially become virtual keys.
We’ll assign the following functionality to each key:

Home key – Leave the app and go back to the home screen. Luckily, we don’t really have to deal with this one since the operating system already takes care of it.

Back button – Return to the previous page in the app.

Menu button – Show our app menu.

Search button – We will not do much with it in this tutorial as it goes for searching, but we will handle the search button press to return a message.

Corona also lets you capture the volume up/down or the D-Pad “up,” “down,” “left,” “right” and “center” buttons available on some Android devices in a similar way. You can find more information at Ansca’s Android key events documentation here.

Lets see how to do this with Corona SDK.

I created a little demo app that captures the Menu, Back, and Search events, where you can navigate between 5 scenes (menu, scene1, scene2, scene2.1 and scene3).

The full code is pretty long, but mostly because each scene is inside a storyboard template. So, let’s look at the part of the code where we handle the button events:

Dissecting the code, “event.phase” is the state of the key (up or down), while “event.keyName” is the name of the key (supported keys are: "back," "menu," "search," "volumeUp," "volumeDown" and D-Pad’s "up," "down," "left," "right").