Home Mobile LiveCode Mobile Development Beginner's Guide

LiveCode Mobile Development Beginner's Guide

By Colin Holgate
books-svg-icon Book
eBook $28.99 $19.99
Print $48.99 $28.99
Subscription $15.99 $10 p/m for three months
$10 p/m for first 3 months. $15.99 p/m after that. Cancel Anytime!
What do you get with a Packt Subscription?
This book & 7000+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook + Subscription?
Download this book in EPUB and PDF formats, plus a monthly download credit
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook?
Download this book in EPUB and PDF formats
Access this title in our online reader
DRM FREE - Read whenever, wherever and however you want
Online reader with customised display settings for better reading experience
What do you get with video?
Download this video in MP4 format
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with video?
Stream this video
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with Audiobook?
Download a zip folder consisting of audio files (in MP3 Format) along with supplementary PDF
What do you get with Exam Trainer?
Flashcards, Mock exams, Exam Tips, Practice Questions
Access these resources with our interactive certification platform
Mobile compatible-Practice whenever, wherever, however you want
BUY NOW $10 p/m for first 3 months. $15.99 p/m after that. Cancel Anytime!
eBook $28.99 $19.99
Print $48.99 $28.99
Subscription $15.99 $10 p/m for three months
What do you get with a Packt Subscription?
This book & 7000+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook + Subscription?
Download this book in EPUB and PDF formats, plus a monthly download credit
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook?
Download this book in EPUB and PDF formats
Access this title in our online reader
DRM FREE - Read whenever, wherever and however you want
Online reader with customised display settings for better reading experience
What do you get with video?
Download this video in MP4 format
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with video?
Stream this video
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with Audiobook?
Download a zip folder consisting of audio files (in MP3 Format) along with supplementary PDF
What do you get with Exam Trainer?
Flashcards, Mock exams, Exam Tips, Practice Questions
Access these resources with our interactive certification platform
Mobile compatible-Practice whenever, wherever, however you want
  1. Free Chapter
    LiveCode Fundamentals
About this book
LiveCode is a tool for developing mobile apps designed for those who don't want to use Objective-C, C++ or Java. Although it is a tool full of rich features to create apps it can be challenging to get beyond the basics and build interactive and fun apps. Using this book, you can develop various apps and this book guides you through "till you upload the apps in the appstore."LiveCode Mobile Development Beginner's Guide" will explain how to create applications with the easiest, most practical cross platform framework available, Livecode Mobile and upload the apps to the appstore with minimal effort.Throughout the book, you'll learn details that will help you become a pro at mobile app development using LiveCode. You begin with simple calculator application and quickly enhance it using LiveCode Mobile. Start by learning the interface controls for videos and images of LiveCode's environment. Dig into configuring devices, building user interfaces, and making rich media applications, then finish by uploading the mobile applications to App Stores. You will learn how to build apps for devices such as iPhone, Android with the recently developed LiveCode Mobile through sample applications of increasing complexity.
Publication date:
July 2012
Publisher
Packt
Pages
246
ISBN
9781849692489

 

Chapter 1. LiveCode Fundamentals

Is this chapter for you?

LiveCode has an English-like programming language, a graphical development environment, and an easy-to-understand structural metaphor. When you create an application, you spend more time thinking about how to implement the different features, and less about the complexities of the tool you are using. But if you've never used LiveCode before, it's still going to be unfamiliar at first. This chapter will bring you up to speed, ready for the later chapters that will require that you are more familiar with the terminology and features of the tool.

LiveCode is easy, but there are thousands of easy things to learn! Throughout the book we will look at the latest of those easy things, particularly those related to mobile applications, but first we should go over some of the basics.

In this chapter we shall:

  • Become familiar with the LiveCode environment

  • Investigate the hierarchy of a LiveCode "stack"

  • Create a simple calculator application

  • Learn about the many different interface controls

So let's get on with it...

 

Background history and metaphors


Many development tools just present a programming language and interfaces to system routines. Higher-level tools often present the same things, but structured in such a way that you can think of real world metaphors for the different aspects of the tool. LiveCode is very much like that, and its metaphor is a stack of cards. This metaphor originated with Apple Computer's HyperCard authoring tool, created by Bill Atkinson in the mid-1980s. The first version of HyperCard was released in August 1987, and it became a huge hit in both education and multimedia. Companies such as The Voyager Company published entire product lines that were created using HyperCard.

Other companies produced tools that were very much like HyperCard, but that also tried to give the user more features than were in HyperCard. The most prominent of those tools were SuperCard, Plus, and MetaCard. Plus went on to have an interesting life, the product itself became Windows-only (it was cross-platform at first), but later the same code ended up in the cross-platform tool Oracle Media Objects. All of these tools perpetuated the metaphor of a stack of cards.

MetaCard was most notable for the fact that it was multi-platform, not just cross-platform. Stacks, the general term used for documents created by these tools, made with MetaCard could run on Unix and Linux systems, as well as Mac and Windows. Alas, it was somewhat ugly! The Scottish company RunRev made a product that was an attempt to present MetaCard in a more appealing way. Eventually RunRev acquired MetaCard, and since 2003 RunRev has continued to build upon MetaCard, using the product name "Runtime Revolution", later renamed to LiveCode.

Under the HyperCard variation of the metaphor, documents consisted of cards that held buttons, fields, and bitmap graphics, backgrounds that held a set of cards, and stacks that held a set of backgrounds. LiveCode takes a slightly different approach, and rather than having backgrounds that hold cards, it allows you to group any set of interface controls and set those to act as if they are a background entity. This ends up being more flexible, though slightly alien to people who have used HyperCard a lot.

Both HyperCard and LiveCode provide ways to extend the hierarchy further. You will be able to take other stacks and put them into use. To save rewriting the same set of functions in every stack, you might choose to have a stack dedicated to those functions, and then add that stack to the "stackinsuse", using the command:

start using stack "utility stack"

Additionally you can write externals, which are commands and functions written in the C language, which can extend LiveCode's abilities even further.

 

You do have LiveCode, don't you?


If you haven't yet installed LiveCode, go to this web page: http://www.runrev.com/downloads/. You will need to create an account to be able to download the trial version. If you plan to go on to buy LiveCode, read through this page: http://www.runrev.com/products/livecode/license-types-overview/ to understand the many license variations there are. As a rough guide, based on the price at the time of writing, to create mobile applications that are free, it would be $99, or if you wanted to make apps that you could charge for, it would be $499. Each extra platform that you want to publish to would be another $99.

Once you have downloaded the trial version, or bought one of the licenses, why not go ahead and launch it!

 

Learning the lay of the land


When you first open LiveCode you are shown a Start Center window, which functions as a way to open recent documents, a list of links to forums, and getting started information. It also provides a way to view promotional information. It does no harm to keep that window open, but if you do happen to close it you can reopen the Start Center from the Help menu.

As you look at LiveCode for the first time you will notice a toolbar along the top of the screen, just below the menu bar. Take note of the items on the right-hand side, User Samples, Tutorials, Resources, and Dictionary. These areas are filled with information that will help you to get started with LiveCode. The Dictionary is something that you will use a lot, and just browsing through the entries will either answer your immediate question or give you advanced information about issues you'll run into later.

The Help menu also provides access to a User Guide and several release note files. Consult the User Guide to read in more depth about features mentioned here.

Tip

Online lessons

In addition to the resources you see inside LiveCode itself, there is a tremendous amount of information and tutorials on the RunRev website. A good starting point would be: http://lessons.runrev.com/

The following screenshot shows the windows and palettes that we're going to be using for now, as well as the document window, which shows a simple calculator that we will soon build:

Main windows

In addition to the document window itself, these are the main windows that we will need to be familiar with for now:

  • Tools palette

  • Inspector palette

  • Message Box

The upper area of the Tools palette shows all of the interface controls that you will need to create an interactive application. Below them are a set of tools for editing vector graphics, and a set of tools for editing bitmap graphics.

The Inspector palette shows all of the options for the control that you currently have selected. In the above screenshot nothing is selected, and so the Inspector palette is showing information about the stack itself.

The Message Box is a window that lets you try out either single or multiple lines of code. You will be able to invoke functions in your stacks too, making it a very handy way to test individual functions while you are tracking down issues. We'll use the Message Box in later chapters.

As suggested above, you should read the User Guide to get a deeper understanding of these windows, but let's try putting together something simple for now, to get you more familiar with using the Tool palette.

 

Time for action – it's a drag, but you'll like it!


You build things in LiveCode by dragging icons from the Tools palette to the Stack window. If the palettes are not already open, the Inspector palette can be opened by clicking the icon on the left-hand side end of the toolbar, or selecting one of the inspector menu items in the Object menu. The Tools palette can be opened by selecting Tools Palette from the Tools menu. To do this, perform the following steps:

  1. From the File menu, select New Mainstack.

  2. In the Tools palette, click on the Edit tool (the top right-hand side icon).

    Tip

    Select Edit, or not…

    In LiveCode you can drag controls from the Tools palette to the card window without first selecting the Edit tool. However, if you are in the Run tool you will not be able to select the control in order to adjust its position or size, and so in these instructions we are intentionally selecting the Edit tool before adding controls to the card window, just to be sure.

  3. Drag icons from the upper section of the Tools palette to the stack window.

  4. Try the layering options at the bottom of the Object menu.

  5. Select more than one item, and experiment with the Align Objects options in the Inspector palette. The align options are shown automatically when you select multiple objects, but you can also select Align Objects from the drop-down menu in the Inspector palette. You won't see that option if only one object is selected. Here we see the options, because three buttons are selected:

  6. Select a single button, and in the Inspector palette enter a Name and a Label. If you don't see the name and label fields, make sure you have selected Basic Properties from the Inspector pallet's drop-down menu.

  7. Add several more controls to the card window, and practice aligning and naming the controls. You can also resize them by dragging on the handles that you see on the corners and the sides, while the control is selected. Here is how it could look if you had added some buttons, a field, a tab panel, and a video player control:

What just happened?

Hopefully you will have made a random bunch of interface controls, perhaps some that are nicely lined up too! Now delete them all, and get ready to make the simple calculator interface.

But first we should go over some of the structure and hierarchy of a LiveCode stack, and also create some basic navigation.

 

Creating a hierarchy


Everything goes somewhere, but having things in the wrong place can lead to problems. So we should learn more about the structure of a LiveCode stack.

Stack structure

As described in the Background history and metaphors section of this chapter, LiveCode uses a stack of cards metaphor. When you make a new stack you, in effect, have a single-card stack of cards. However, even the simplest application is likely to have more than one card. For example, there could be a splash screen, a title card, cards for the actual task at hand, and a credits page. In the calculator stack we will use two cards. The Tools menu includes an option to view the structure of the stack, by showing the Application Browser:

Where code goes

In programming languages like the one in LiveCode, code is referred to as scripts, while methods or functions are known as handlers (though in LiveCode a handler that returns a value is also called a function). Projects made with harder-to-use programming tools often consist of dozens of external text files, one for each model, view, or controller. In LiveCode this is simpler; the scripts are attached to the object that needs that code.

To deal with user interaction in other tools you will have to write code that receives the event (perhaps just a mouse-click on a button), and to then perform the relevant action. In LiveCode there is a message path that takes care of these events and passes them up the hierarchy. If you click on a LiveCode interface control that doesn't have a mouse event handler, the click goes up the hierarchy to the card level. If the card doesn't have a handler for that event, it continues up to the stack level.

You can have additional levels of hierarchy, by putting other stacks into use, but for our purposes we just need the button, card, and stack hierarchies.

This message hierarchy allows us to place the code needed by several interface controls into a higher level, available to all of those controls. One such case will be with the calculator's number buttons; each one needs to do exactly the same thing, and by putting that code into the card level, each of them can make use of that single handler.

There is no performance advantage to having the shared handler in the card level, or much of a file size improvement, but as you are developing the code for the simple calculator, you can make changes to the single card script, instead of 11 individual calculator button scripts.

We will now start to build the calculator, and add scripts to the 14 buttons, a field, and the card.

Tip

Downloading the example code

You can download the example code files for all Packt books you have purchased from your account at http://www.packtpub.com. If you purchased this book elsewhere, you can visit http://www.packtpub.com/support and register to have the files e-mailed directly to you.

 

Time for action – making and navigating between cards


A calculator doesn't really need a title screen, but we'll make one anyway, in order to practice adding scripts and doing some basic navigation. You can either take your cleared-out stack from earlier, or start a New Mainstack from the File menu.

  1. Select New Card from the Object menu.

  2. Use the View menu to either go to the previous card (Go Prev), or first card (Go First).

  3. Make sure you have the Edit tool selected in the Tools palette, and drag a Label field to the middle of the card window. In this case you can easily see which one is the Label field (it says Label: in the icon), but as a general tip, you can point to controls in the Tools palette and see a help tip that shows what kind of control it is.

  4. In the Basic Properties section of the Inspector palette, uncheck the Don't wrap check box.

  5. Type title into the Name entry field.

  6. Choose Contents from the Inspector drop-down menu, and replace the initial text that says Label: by typing Simple Calculator into the contents entry field.

  7. Choose Text Formatting from the drop-down menu, and click on the align text center button, which is the middle of the three Align buttons.

  8. Change the Font, Size, and Style options, to make a nice looking title, resizing the field itself until you like how it looks:

  9. Drag a Push button (the second icon from the top left-hand side in the Tools palette) from the Tools palette, and place it below the title field.

  10. In the Inspector, choose Basic Properties from the drop-down menu (it's the menu that says Text Formatting in the screen shot above), type in Begin into the Name entry field. LiveCode will automatically show the same text as the button's label, even though you didn't type it into the Label entry field.

  11. You can go into the text formatting options for buttons too, if you wish!

  12. Mentally prepare yourself - we're about to type in our first script!

  13. With the button selected, choose Object Script from the Object menu. You can also right-click on the button itself, and select Edit Script.

  14. The Script window will appear, and will show a starter script, of on mouseUp, (empty line), and end mouseUp as shown in the following screenshot:

  15. Complete the script by typing in go next into the blank line to give you this final script:

    on mouseUp
    go next
    end mouseUp
  16. Close the script window, and click on Yes when asked if you want to save the changes.

  17. Choose the Browse tool from the Tools palette (the upper left-most tool, that looks like a regular cursor arrow), and click on the Begin button that you just made. All being well you're now looking at a blank card. Don't worry, you didn't just delete the title field and button! You're now on the second of the two cards that you made earlier. Use the View menu again to go back to the first card, to try the button again.

  18. Save! From the File menu, choose Save, and save the stack, with the name Simple Calculator, somewhere you can easily find later. Perhaps you could make a folder to hold the stacks you will make while reading this book.

What just happened?

That may have seemed like a lot of steps, but we did create the two cards we need, laid out a nice looking title field, and created a Begin button with its own script. In reality those steps take under two minutes, and even less as you gain experience in LiveCode.

Pop quiz – best name?

If you want to make it big in the multimedia authoring tool world, which of these names would be a bad choice?

  1. Henry

  2. Bill

  3. Bob

  4. Kevin

 

Making a simple calculator application


With even a basic familiarity with LiveCode, you can start to make something of use. Here we will make a very simple calculator stack.

Inspector clues, oh…

You will find yourself using the Inspector palette a lot, so take a moment to study how it behaves. When you select an object on the card you will see that the Inspector palette changes its appearance, sometimes even its height, to show the options for the item you have selected. It is smart enough to notice when you have selected multiple items, and will then show the align tools.

Sometimes you will want to keep an Inspector palette set to view the options of a particular object on the card, and to not switch to show a different object as you make other selections. In the upper right-hand side corner of the Inspector palette is a padlock icon, which will let you lock the inspector to the current object.

So far, most of the Inspector palette options haven't affected us, but one that is about to be relevant is the fact that you can set a name for an item that is different to its label. You may know from other programming languages, and this also applies to LiveCode, that some names are less legal than others. Perhaps you can't have spaces in the name, or use a colon, or backslash. If you name a button with a number, Button "1" may not be Button 1, and that could lead to confusion.

For the calculator keys we will set a label to make it look correct, and a name that doesn't lead to confusion. Speaking of those calculator keys…

 

Time for action – making the calculator buttons


Using the first screenshot from this chapter as a guide, let's build the calculator buttons (the scripts you will type are also listed later on, if you want to make sure you typed it correctly):

  1. If you're not already there, go to the second card (the currently empty one).

  2. Make sure the Edit button is selected in the Tools palette, and drag a Push button to the card, in the position of the button with the label 7.

  3. In the Basic Properties of the Inspector palette, set the Style drop-down menu to Rounded Rectangle (in real life you would take the time to have nice graphical buttons, here you are just matching my ugly "programmer art"!).

  4. Set the name of the button to number7, and the label to 7.

  5. Select Object Script from the Object menu to see the starter script as you did with the Begin button.

  6. In the empty line between on mouseUp and end mouseUp, type numberPressed the label of me.

  7. Close and save the script.

  8. Select the button and make a copy of it, by choosing Duplicate Objects from the Edit menu, and position it where the button with the label 8 will be. Copy/Paste and alt-drag are two other ways to duplicate an object.

  9. Set the name to number8, and the label to 8.

  10. Repeat steps 8 and 9, for the buttons 9, 4, 5, 6, 1, 2, 3, 0, and the decimal point, using the corresponding number instead of 8. For the decimal point, set the name to decimalpoint.

  11. Duplicate one of the buttons again, name the new button divide, and type / for its label.

  12. Select Object Script for the divide button, and change numberPressed in the middle line to operatorPressed, making the whole line read as operatorPressed the short name of me.

  13. Duplicate the divide button three more times, and set the names to multiply, plus, and minus. Set the labels to *, +, and -.

  14. Duplicate the divide button again, giving the name equals to the button and setting the label to =, and changing the middle line of script to say equalsPressed

  15. Duplicate the equals button, and set the new button's name to toggleSign and label to +-, then change the middle line of script to toggleSign.

  16. Duplicate the equals button, set the new button's name to clear and label to C, then change the middle line of script to be clearPressed.

  17. Drag a Label field from the Tools palette, and in the Inspector palette choose Text Formatting from the drop-down menu. In the Text Formatting settings choose a nice looking font, right justified text, and a large font size. Name the field display.

  18. Edit the script of the display field. With fields you don't get the starter script that you get with buttons, so you will need to type the mouseUp lines yourself. Type the following three lines:

    on mouseUp
    set the clipboarddata["TEXT"] to me
    end mouseUp
  19. Move all of the buttons into their right spots, and select sets of buttons to then use the Align tools to make your calculator layout match the screenshot.

  20. Save!

What just happened?

Quite a lot just happened! We have now made all of the card level objects, and typed in their scripts. Most of the scripts are "calling" up to a card level handler that we will be setting up next. Before we do that it's worth trying to understand some of the lines we just entered.

Verbosity, synonyms, and "me"

The near-English nature of the programming language in LiveCode is amazingly powerful, but rigidly so. In some other tools you have a choice of whether you use verbose English-like syntax, less verbose, or what is called dot syntax. The Lingo language, in Adobe Director, is a good example to compare to.

Suppose we want to change the text inside a field that is the first entry of a Director movie's cast, we can use verbose syntax:

put "hello world" into the text of member 1 

or slightly less verbose syntax:

the text of member 1 = "hello world"

or dot syntax:

member(1).text = "hello world"

In LiveCode there isn't that choice - what you type has to be in the form of:

put value into container

You do have a choice about whether you use a long version of a word, a short version, or an abbreviated form. There are also synonyms, which allow you to use a word that makes more sense to you.

Here are two ways of saying the same thing, with the second variation using an abbreviated form of the key words:

put character 3 of word 2 of card field "name of field 1" into aVariable

put char 3 of word 2 of fld 1 into aVariable

When you are dealing with the contents of the object that has the script that is running, you can use the keyword me to save on some typing, and LiveCode will also try to work out what you have in mind, if possible.

Take the lines we have entered as examples:

numberPressed the label of me

numberPressed will propagate up to a card handler we will add (soon). the label of me will look at the Label that you set for the object that the script is inside of.

set the clipboarddata["TEXT"] to me

In this case, me would normally refer to the object (as is the case with the label of me), but because we gave the extra clue of ["TEXT"], LiveCode knows that it's the text contents of the field that has that script, and not the field itself. Still, because there is the potential for confusion when reading your own code later, you could add a couple of words to make the meaning more clear:

set the clipboarddata["TEXT"] to the text of me

Tip

By the way, that display field script is not needed for the calculator to work. It's just there so that at any time you can click on the field and have the current value be copied to the clipboard, to paste into other applications.

You might choose to be more verbose than is needed, just for readability reasons, and in these chapters that is going to be the case. Using:

put the text of me into textvariable

makes it easier to tell what is going to happen than if you use the equally valid:

put me into textVariable

In either case, as it's a field, LiveCode knows what you meant.

Now look at the script in which we typed short name of me - what's that all about? Objects in LiveCode have a lengthy description of where they are located, e.g. "button "buttonname" of card id 1234 of stack "path/to/stack.livecode"". In the calculator application we need only the single word you set as the name of the button. If we asked for name of me, it would still say button "buttonname". To just grab the name itself, we use short name of me.

There are times when you will want to use the other variations of "name", including the long name and the abbreviated name, which you can read about in the LiveCode Dictionary entry for "name". In addition to a description of the different ways to use "name", there are a number of cautions shown.

Tip

Case sensitivity

If any advanced LiveCode users are reading this chapter, they may notice that in some instances I have the case wrong. LiveCode doesn't mind what case you have used, and so when I incorrectly said clipboarddata instead of clipboardData, it didn't matter. This isn't unique to LiveCode, but it is common amongst English-like programming languages to not demand that the user gets the case exactly right before the command will work.

Adding the card handlers

If you had dared to try using the calculator buttons, you would have seen a lot of script errors. We need to add in the card level handlers to be at the receiving end of the calls that the buttons are making. Instead of walking you through typing one line of code at a time, it would probably be quicker to present the lines in one go and explain what each line does. As a practice run, here are the lines that we have entered so far:

On all of the number buttons and the decimal point button, you should have this script:

on mouseup
   numberPressed the label of me
end mouseup

on mouseUp is triggered when you press and release the left mouse button while on the button, numberPressed will call a card handler named "numberPressed", passing with it the Label that you had set for the button that holds this script.

The C (clear) button has this script:

on mouseUp
   clearPressed
end mouseUp

clearPressed will call a card script named "clearPressed"

The other buttons all work in much the same way - they call a handler of the name used, which we're about to add to the card script. The following is the script for the +, -, *, and / buttons, passing the name of the button in question to the card level:

on mouseUp
   operatorPressed the short name of me
end mouseUp

And this is the one on the +- button:

on mouseUp
   toggleSign
end mouseUp

The display field has this script:

on mouseUp
   set the clipboarddata["TEXT"] to me
end mouseUp

In the case of the field, it's only processing one line of code, so no need to put that up on the card level, unless we had a lot of fields doing the same thing.

So, why don't we add all those card level scripts? Here they are, one at a time, with an explanation of how each one works:

But wait… we haven't yet talked about variables. Hold that thought, while we see how LiveCode handles variables.

Variable types in LiveCode

Generally speaking, variables are memory locations where you store values that you need to access later. In most programming languages you can dictate which routines have access to which variables. Less English-like languages may use the terms "public", "private", and "protected". Things are not all that different in LiveCode but here the words used describe more the region where the variable can be used. If a variable is to be readable everywhere, it would be "global". If it's just to be used in the current script, it's "local".

LiveCode also has custom property variables, and many people would use those for the calculator button values instead of relying on the label of the button. We'll perhaps use them later!

Now, where was I… oh yes, card level scripts:

This is the first line of the card script:

global currenttotal,currentvalue,currentcommand,newnumber

As we just discussed, these are variables that will allow all of the handlers to pass values to each other. In this case the variables could have been local, but you may often decide to use global instead, thinking that a case may come up later where you need to access the variables from outside the script you're in.

It's good to reset things when you first start, and LiveCode has an opencard event that we can use to do this. The following code resets things:

on opencard
   clearpressed
end opencard

on clearpressed
   put true into newnumber
   put 0 into field "display"
   put 0 into currenttotal
   put 0 into currentvalue
   put empty into currentcommand
end clearpressed

Having the reset lines in the clearPressed handler will allow us to call it at other times and not just when the card opens. We can call it directly when clicking on the C (clear) button which will zero out the display field, the running total for your calculation, and the last number that you entered into the calculator. It also clears the variable that is used to remember which operator button you last pressed, and a boolean (true/false) variable used to recognize whether a number button you press should clear the display or append to the display.

All of the numbered buttons, and the decimal point button, call this handler:

on numberPressed n
   if newnumber is true then
      put n into field "display"
      put false into newnumber
   else
      put n after field "display"
   end if
end numberPressed

The n after the handler name is a parameter variable that stores what was sent to the handler. In this case it's the label of the button that was pressed. All this routine needs to do is add the character to the end of the display field, except for when you are typing in a new number. That's where the newNumber boolean variable comes in - if that is set to true, the incoming character replaces the contents of the display field. However, if it's false, the character is added to the end of the field.

This is the handler for when you press the +, -, *, or / buttons:

on operatorPressed operator
   if currentCommand is empty then
      put field "display" into currentTotal
      put operator into currentCommand
      put true into newNumber
   else
      put operator into currentCommand
      equalsPressed
   end if
end operatorPressed

When you use a calculator, you type in a number, an operator, and then another number, followed by either another operator or the = button. At the time you press the operator button there is no way to know the result, as you haven't yet entered the next number in the calculation. So, we remember the operator till you have entered the next number. If the currentcommand variable doesn't already have a value, we store the display field text into the currenttotal variable, the operator character that you pressed into the currentcommand variable, and make sure that newnumber is set to true. Doing this makes sure that the next number button you press will clear the display field. If currentcommand already has a value, we replace it with the new value, and then call the same handler that is used when you press the = button.

There are most likely shorter ways to deal with the = button being pressed, but here we'll use several if statements, and run the appropriate calculation code:

on equalsPressed
   put field "display" into currentValue
   if currentCommand is empty then exit equalsPressed
   if currentCommand is "divide" then put currentTotal / currentValue into field "display"
   if currentCommand is "multiply" then put currentTotal * currentValue into field "display"
   if currentCommand is "minus" then put currentTotal - currentValue into field "display"
   if currentCommand is "plus" then put currentTotal + currentValue into field "display"
   put field "display" into currentTotal
   put true into newNumber
   put empty into currentCommand
end equalsPressed

The contents of the display field are stored in the currentValue variable , and the last operator button you pressed (that is stored in currentCommand) is looked at, to see what happens next. If there wasn't a previous operator (as would be the case if you pressed = twice in a row) we ignore the button press and exit the routine. For the four operators, we do the appropriate calculation. Afterwards, we store the new running total into the currentTotal variable, make sure that the newNumber boolean variable is set to true (so that the next number button pressed will clear the display field), and we forget the last operator button that was pressed, by putting empty into the currentCommand variable.

One thing to note is that LiveCode is smart enough to know that the text string inside the display field is to be treated as a floating point number.

For the last handler, togglesign, insert the following code:

on togglesign
   if character 1 of field "display" is "-" then
      delete character 1 of field "display"
   else
      put "-" before field "display"
   end if
end togglesign

This is a very simple routine, that doesn't have to understand that it's floating point numbers being represented. It simply looks to see if the first character is a minus or not, and if it is, it deletes the character. If not, it inserts the hyphen that LiveCode will later interpret as a negative value.

Pop quiz – try to remember…

As you get to learn a new tool you can end up taking a lot of time remembering where the thing is that you need. You know what you want to do, you know how to do it, but you can't remember where that thing is located! Where did you go to set the text styling for the calculator's title field?

  1. The Edit menu.

  2. The Object menu.

  3. The Text Formatting section of the Inspector palette.

  4. The Text menu.

Extending the calculator

It is possible to add more features to the simple calculator. If we consider how the buttons are named, and the functions in the card script, you can start to see what would be involved in adding a new ability:

  • The calculator operator buttons are named so that the card script knows which one you clicked on.

  • When the = button is pressed, there are a set of if statements in the equalspressed handler that determine what happens next.

Have a go hero – getting to the root of things

On Windows you can make a square root symbol with Alt+251, and on Mac with Option+v. Unfortunately LiveCode doesn't like those as button labels! At least on Mac, when you type that character into the Inspector palette, the character immediately vanishes. One work-around would be to use the message box, and type this:

set the label of btn "squareroot" to "√"

That should give you the right symbol as the button label.

LiveCode has a square root function; typing this into the Message Box would produce the square root of 10:

put sqrt(10)

Now, armed with the above information, try to add a square root feature to the calculator.

 

Other interface controls


So far we have only had to look at buttons and fields to be able to create the calculator. In later chapters we will use many more controls, so let's take a sneak peek at those.

Video player control

If your system has QuickTime installed, LiveCode can play QuickTime movies, using the Player control type. Those can be added to the card in several ways, as well as by using a script command as described in the following points:

  • A file can be added from your hard drive by selecting Import as Control/Video File from the File menu

  • An empty player can be created by selecting New Control/Player from the Object menu

  • A player control can be dragged from the Tools palette to the card

  • A player can be created with code, including setting its name:

    new player "player name"

Having added the player to the card, you can then set which video file is to be played by entering the file path or URL of the file under the Basic Settings of the Inspector palette. You can also set the path to the video with the following script:

set the filename of player "player name" to "file path or URL"

Still image control

In the same way that you just saw for playing video, still images can also be added to a stack. All of the options shown for adding a video player can be used for images. Here, for example, is the script needed to add the RunRev company logo to the card:

new image "revlogo"
set the filename of image "revlogo" to "http://www.runrev.com/runrev-globals/corporate-nav/images/runrev.gif"

Rollover buttons

Images that you import can be used as icons in a button. To set up a button so that it has a nice idle state image, and an associated highlight image, you would do the following steps:

  1. Select File | Import As Control | Image File…

  2. Choose the images that represent the idle and highlight states, and click on Open.

  3. Select the button that you wish to look like these images, and under Icons & Border in the Inspector palette, click on the magic wand button to the right-hand side of the top entry (Icon).

  4. In the dialog that appears, select This Stack from the drop-down menu.

  5. Select the image that is the idle state for the button.

  6. Click on the magic wand button next to the Hover entry, and choose the highlight state image.

  7. Under Basic Properties, choose Transparent Button from the Style drop-down menu.

  8. Uncheck the boxes for Show name, Auto hilite, and Shared hilite.

  9. Resize the button to be big enough to show the image.

  10. Select each of the original images, and under Basic Properties, uncheck the Visible box.

Here we can see two images that have been imported in order to give the Begin button a more iOS appearance. The button is selected, and the Inspector palette shows the icon selection choices.

Then when you choose an image to use, the button itself will be updated. In this case the Hover Icon has been set to the darker version of the graphic, but as shown here, the button still needs to be resized.

Many More Controls…

LiveCode has a lot of different controls. Many are just slight variations, but there are plenty that are quite different from each other. Look at the Object menu, and then New Control. As you'll see the list is very long!

 

Debugging


If you did go ahead and try the calculator before we had entered all the scripts it needed, you most likely would have got to see the script debugging in action. Hopefully you managed to cope with what you saw; it can be overwhelming at first. The following screenshot is what it would have looked like:

Most of what you see is the same as when you edit scripts, but if you do see the debug variation you are actually in a paused state, a freeze frame of the program as it runs. In this example the program stopped because line 46 is looking for a field named dis play, and there isn't such a field, it should be display.

The error message at the bottom makes it clear that the error is something to do with the field name, and you would quickly spot the typo. Sometimes though you may need to inspect the variables, to make sure they contain the values you think they should. The Variables tab will show a list of those.

An unexpected problem is the one time you may see the debugger, but when developing a script you are able to set Breakpoints by clicking in the column just to the left-hand side of the line number you want to halt the program at.

Once the script is halted by a breakpoint, you can use the row of buttons at the top to step through the code. Those buttons are:

  • Continue will set the script running again

  • Stop will stop the script running, so that you can make changes

  • Show next statement will show an indicator to the left-hand side of the current line

  • Step into next statement is used for stepping into a different handler

  • Step over next statement will go onto the next statement in the current handler, without stepping into a handler mentioned on the current line

  • Step out of current handler is used to skip the remaining lines in a handler that you had previously stepped into, and exit back out to the handler that called the current one

You will become more familiar with the script editor and debugger as you go along, but that should get you started!

 

RunRev's online tutorials


In this chapter we have covered just enough to make you familiar with the environment, to practice using some controls, and to do a little script writing. There is quite a lot to LiveCode as a tool, and so you may be interested in looking into other topics, or going into more depth than is covered here.

A good starting point would be RunRev's own set of online tutorials, which are located in the following location:

http://lessons.runrev.com/

Type into the search box words that describe your area of interest, and you will see a list of articles on that topic.

 

Summary


Having created a simple calculator from scratch, you should now be more familiar with the LiveCode environment.

In this chapter we covered:

  • Buttons, fields, scripts, and stack structure, to get an understanding of how they work together.

  • Several short scripts, to illustrate the English-like syntax used by LiveCode.

  • The script window, and how you would debug a script.

  • Other interface controls, in preparation for using them in later chapters.

We also discussed the kinds of variables used by LiveCode, and how it can use abbreviated commands and synonyms.

Now that we've learned enough to make regular LiveCode stacks, we need to download and install additional software from Google and Apple that is required for publishing a stack to a mobile device, and then begin to try out mobile specific features, both of which are covered in the next chapter.

About the Author
  • Colin Holgate

    Colin Holgate was originally trained as a telecommunications technician in the Royal Air Force, but with the advent of the personal computer era he transitioned to working as a technical support engineer for companies that included Apple Computer UK. In 1992 he moved to the USA, to become a full time multimedia programmer, working for The Voyager Company. In that role he programmed several award winning CD-ROMs, including A Hard Day’s Night and This Is Spinal Tap. For the last 12 years Colin has worked for Funny Garbage, a New York City based web design company. In addition to using Adobe Director and Adobe Flash for online and kiosk application, he has used LiveCode for in-house production tools. At the introduction of LiveCode for Mobile at the RunRevLive Conference in 2011, Colin entered, and won a contest to create a mobile application made with LiveCode.

    Browse publications by this author
Latest Reviews (1 reviews total)
LiveCode Mobile Development Beginner's Guide
Unlock this book and the full library FREE for 7 days
Start now