Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Save more on your purchases now! discount-offer-chevron-icon
Savings automatically calculated. No voucher code required.
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Conferences
Free Learning
Arrow right icon
LiveCode Mobile Development Beginner's Guide (2nd Edition)
LiveCode Mobile Development Beginner's Guide (2nd Edition)

LiveCode Mobile Development Beginner's Guide (2nd Edition): Create interactive mobile apps for Android and iOS with LiveCode

Arrow left icon
Profile Icon Colin Holgate Profile Icon Joel W Gerdeen
Arrow right icon
$54.99
Full star icon Full star icon Full star icon Empty star icon Empty star icon 3 (1 Ratings)
Paperback May 2015 256 pages 1st Edition
eBook
$29.99 $43.99
Paperback
$54.99
Subscription
Free Trial
Renews at $19.99p/m
Arrow left icon
Profile Icon Colin Holgate Profile Icon Joel W Gerdeen
Arrow right icon
$54.99
Full star icon Full star icon Full star icon Empty star icon Empty star icon 3 (1 Ratings)
Paperback May 2015 256 pages 1st Edition
eBook
$29.99 $43.99
Paperback
$54.99
Subscription
Free Trial
Renews at $19.99p/m
eBook
$29.99 $43.99
Paperback
$54.99
Subscription
Free Trial
Renews at $19.99p/m

What do you get with Print?

Product feature icon Instant access to your digital eBook copy whilst your Print order is Shipped
Product feature icon Paperback book shipped to your preferred address
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
OR
Modal Close icon
Payment Processing...
tick Completed

Shipping Address

Billing Address

Shipping Methods
Table of content icon View table of contents Preview book icon Preview Book

LiveCode Mobile Development Beginner's Guide (2nd Edition)

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. However, if you've never used LiveCode before, it's still going to be unfamiliar at first. This chapter is to bring you up to speed and make you ready for the later chapters that will require you to be more familiar with the terminology and features of this tool.

All of LiveCode is easy, but there are thousands of easy things to learn! Throughout the book, we will look at these things, that you can use for mobile applications in particular, but first, we should go over some of the basics.

In this chapter, we will:

  • 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 only present a programming language along with programming interfaces to system routines. Higher-level tools often present the same things, but structured in such a way that it is possible to come up with 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, which was 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 sectors. Companies such as The Voyager Company, published its entire product line which was created using HyperCard.

Other companies produced tools that were very much like HyperCard, but they also tried to give the user more features than were in HyperCard. The most prominent of these 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 Oracle Media Objects cross-platform tool. All of these tools perpetuated the metaphor of a stack of cards.

MetaCard was most notable for the fact that it was multiplatform and not just cross platform. Stacks is the general term used for documents created by these tools, made with MetaCard that ran on Unix and Linux systems, as well as Mac and Windows. Alas, it was somewhat ugly! The Scottish company RunRev made a product that attempted 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, which was later renamed as LiveCode.

Note

In March 2015, RunRev also changed the company name to LiveCode Ltd. This book has many references to http://runrev.com/, and it should still be maintained as such. However, If you have a problem with a URL, substitute it with http://livecode.com/ or do a search on the LiveCode website.

In 2013, RunRev had a successful Kickstarter campaign and raised £494k ($775k) to make LiveCode open source. Version 6.0 of LiveCode was released in April 2013 as the first open source version. This led to an active development cycle with close to 20 stable releases culminating in version 7.0 of LiveCode in October 2014. This edition of this book is based on the version 7.0 of LiveCode.

The highlights of version 7 include Unicode support, display resolution independence, stretchable graphics, hybrid apps using a new browser, Mac Cocoa support, Raspberry Pi support, 64-bit Linux support, and much more. You can read more about version 7 of LiveCode in the October 23, 2014 newsletter issue at http://newsletters.livecode.com/october/issue180/. All LiveCode newsletters are available under the LiveCode Help menu.

In 2014, RunRev had another financing campaign to raise support for HTML5 and raised an additional $395k. This capability and the version 8 of LiveCode with open language support are described further in Appendix, Extending LiveCode.

Under the HyperCard variation of the stack of cards metaphor, documents consist of the cards that hold buttons, fields, and bitmap graphics; backgrounds that hold a set of cards; and stacks that hold 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 background entities. These end 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 are able to link other stacks. To save time rewriting the same set of functions in every stack, you might choose to have a stack dedicated to these functions and you can add that stack to the stackInUse property using the following 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 http://livecode.com/download and download the Community Edition for your development platform. This version is open source and free to use. You will need to provide your name and e-mail which establishes a user account for LiveCode. At the time of writing this book, you also get a free App Design Kit that includes an introductory video and a mobile app2market.livecode template.

If you plan to buy Commercial LiveCode, read through http://www.runrev.com/store/ to understand the many variations of licenses that are there. As a rough guide, based on the price at the time of writing this book, to create mobile applications that are free, the cost would be $99, and if you want to make apps that you could charge for, the cost would be $299. Additional levels of use and support are available at extra cost.

The two editions of LiveCode have a distinctive color scheme too, with the Commercial Edition using blue elements and the Community Edition using green elements.

Once you have downloaded the Community Edition or bought one of the commercial licenses, 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 information to get started, or to view promotional information. There is no harm in keeping that window open, but if you do close it, you can reopen it from the Help menu. You can also use Backdrop by selecting it from the View menu to hide other application windows on your screen.

If you look at LiveCode for the first time, you will notice a toolbar at the top of the screen, just below the menu bar. Take note of the rightmost items, such as Sample Stacks, Tutorials, Resources, and Dictionary. These areas are filled with information that will help you to get started with LiveCode. 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 User Guide and useful links to other information. Check the User Guide section to read in depth about the features mentioned here.

Online lessons

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

This screenshot shows the windows and palettes that we're going to use for now as well as the document window, which is a simple calculator that we will build soon:

Online lessons

Main windows

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

  • Tools palette
  • Inspector palette
  • Message box

The upper area of the Tools Palette shows all the interface controls that you need to create an interactive application. Below these are a set of tools to edit vector graphics and a set of tools to edit bitmap graphics.

The Inspector Palette shows all the options for the control that you currently have selected. In the preceding screenshot, nothing is selected in the calculator app, so the Inspector Palette shows information about the stack itself.

Message Box is a window that lets you try out either single or multiple lines of code. You are 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, 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 how to use 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 on the icon at the left end of the toolbar or by selecting one of the inspector menu items in the Object menu. The Tools palette can be opened by selecting the Tools Palette from the Tools menu and by using the following steps

  1. From the File menu, select New Mainstack.
  2. In the Tools palette, click on the Edit tool (the top-right icon).

To select edit or not…

In LiveCode, you can drag controls from the Tools palette to the card window without selecting the Edit tool. However, you are not able to select the control to adjust its position or size, and so, in the following instructions, we are intentionally selecting the Edit tool before adding controls to the card window:

  1. Drag icons from the upper section of the Tools palette to the stack window.
  2. Try the layering options at the bottom of the Object menu.
  3. 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 this option if only one object is selected. Here, we are able to see the options because three buttons are selected:
    To select edit or not…
  4. 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 pallete's drop-down menu.
  5. Add several more controls to the card window and practice aligning and naming the controls. You can also resize them by dragging the handles that you see on the corners and sides while the control is selected. Here is how the window would look if you add some buttons, a field, tab panel, slider, and video player control:
    To select edit or not…

What just happened?

Hopefully, you will have made a random bunch of interface controls, perhaps some that are nicely lined up too! Now, select the Close and Remove From Memory option from the File menu and create a new Main Stack to make the Simple Calculator interface.

First though, we should go over some of the structure and hierarchy of a LiveCode stack and create some basic navigation.

Creating a hierarchy

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

The stack structure

As described in the Background history and metaphors section, LiveCode uses a stack of cards metaphor. When you make a new stack, you in effect have a single stack of cards. However, even the simplest application is likely to have more than one card. For example, there could be a splash screen, 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 Project Browser or Application Browser. The Project Browser was introduced in the version 6.0 of LiveCode with additional capabilities

The Project Browser panel is a powerful tool that lets you see all the stacks, cards, and controls that are open at the moment, in one window. In addition to getting an overview of everything, you can use it as a remote control to jump between all the parts of your stack and to select and modify buttons, fields, and so on.

Taking the calculator stack that we are about to make as an example, in the following screenshot, we see a side-by-side view of the stack window and the Project Browser panel, where in the Project Browser panel, we have selected one of the buttons in the stack:

The stack structure

The upper area of Project Browser includes a field where you can type and search text to reduce the list of items in the browser to match the ones you have typed. In the upper-left part of the panel, is a gear icon that is used to take you to the preferences of the browser:

Most of the rest of the browser window lets you expand stacks and cards, and choose individual controls on those cards. Clicking on a control in Project Browser highlights it in the stack window and vice versa. Controls can also be reordered to change layers by dragging them up and down. Controls can also be hidden or locked by clicking on the eye and lock icons. The lower area buttons let you do various alignments of the selected controls to add or duplicate the selected control. Hovering over a button shows a popup of what it does.

A longer overview of how Project Browser works is available at:

http://www.runrev.com/newsletter/april/issue151/newsletter4.php.

Where does the code go?

In programming languages, such as the one in LiveCode, code is referred to as scripts and methods or functions are known as handlers (though in LiveCode, a handler that returns a value is also called a function). Projects made with hard-to-use programming tools often comprise dozens of external text files, one for each model, view, or controller. In LiveCode, this is simpler, as 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) to perform the relevant action. In LiveCode, there is a message path that takes care of these events, and passes the event 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 in use, but for our purpose, we just need these three: the button, card, and stack.

This message hierarchy allows us to place the code needed via several interface controls at a higher level available to all of these controls. One case with the calculator number buttons is that each one needs to do exactly the same thing, and by putting that code in the card level, all of them can make use of that one handler.

There isn't a performance advantage if you have the shared handler in the card level or much of a file size improvement, but as you develop the code for the simple calculator example, you can make changes in the single-card script instead of the 11 calculator button scripts.

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

Time for action – making cards and navigating between them

A calculator doesn't really need a title screen, but we'll make one anyway in order to practice adding scripts and to do some basic navigation. Start a new Mainstack from the File menu and open the Inspector palette.

  1. In the Inspector palette, enter the Simple Calculator stack name in the Name field.
  2. Select New Card from the Object menu.
  3. Use the View menu to either go to the previous card (Go Prev) or first card (Go First).
  4. 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 the help tip that shows what kind of control it is.
  5. In the Basic Properties section of the Inspector palette, uncheck the Don't wrap checkbox.
  6. Type title into the Name entry field.
  7. Choose Contents from the Inspector drop-down menu and replace the initial text that says Label: by entering Simple Calculator into the Contents entry field.
  8. Choose Text Formatting from the drop-down menu and click on the Align text center button, the middle of the three Align buttons.
  9. Change the font, size, and style options to make a nice looking title, resizing the field itself until you like how it looks:
    Time for action – making cards and navigating between them
  10. Drag a Push button (the second icon from the top-left corner of the Tools palette) from the Tools palette and place it below the title field.
  11. In the Inspector palette, choose Basic Properties from the drop-down menu (it's the menu that says Text Formatting in the preceding screenshot) and enter Begin in the Name entry field. LiveCode will automatically show the same text as the button's label even though you didn't type it in the Label entry field.
  12. You can go into the Text Formatting options for buttons too, if you wish!
  13. Mentally prepare yourself; we're about to type in our first script!
  14. With the button selected, choose Object Script from the Object menu. You can also right-click on the button itself and select Edit Script.
  15. The script window will appear and show a starter script of on mouseUp, blank line, and end mouseUp, as shown in the following screenshot:
    Time for action – making cards and navigating between them

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

on mouseup
  go next
end mouseup

Now, perform the following steps:

  1. Close the script window and click on Yes when asked whether you want to save the changes.
  2. Choose the Browse tool from the Tools palette (the upper leftmost 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.
  3. Save! from the File menu, choose Save and save the stack with the Simple Calculator name somewhere you can easily find it later. Perhaps, you could make a folder to hold the several stacks you will make while reading this book.

What just happened?

These may have seemed like a lot of steps, but we did create the two cards we needed, laid out a nice looking title field, and a begin button with its own script. In reality, these steps take well under two minutes and will be even quicker to carry out as you gain experience in LiveCode.

Pop quiz – selecting the 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

Answer: 1

In the early days of multimedia, it seemed like everyone had one of just a few popular names. There was Bill Atkinson, who created HyperCard, and Bill Appleton, who created SuperCard. Kevin Calhoun was the lead HyperCard programmer for a while and Kevin Miller is the head of LiveCode. Bob Stein was one of the founders of The Voyager Company and along with Bob Abel who was one of the pioneers in visual effects. Dan was another good choice as there was Dan Winkler, the author of the HyperTalk language, and Danny Goodman, the author of many famous programming books. Henry would be a good name if you wanted to make motorcars or marry lots of queens.

Making a simple calculator application

With even basic familiarity of 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 shows 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 not switch so as to show a different object as you make other selections. In the upper-right 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 from its label. You may know from other programming languages, and this does apply to LiveCode too, 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 this 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 screenshot shown at the start of this chapter as a guide, let's build the calculator buttons (the scripts you will type are also listed if you later want to make sure you typed them 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, to the position of the 7 button.
  3. In the Basic Properties panel 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. Note that numberPressed is a new handler that needs to be defined later. When used, me refers to the current object; in this case, the button pressed.
  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 8 button will be. Copy/Paste and Alt-drag are two other ways to duplicate an object.
  9. Set the name to number8, and 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, let the name be 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 say operatorPressed, making the whole line 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 new button a name equals and a label =, and change the middle line of script to say equalsPressed.
  15. Duplicate the = 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 = button and 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 these three lines in the script: on mouseUp, set the clipboarddata["TEXT"] to me, and end mouseUp. DO enter the quote marks on either side of the word "TEXT".
  19. Move all the buttons in their right spots and select the sets of buttons to then use the Align tools and make your calculator layout match the screenshot.
  20. Save it now!

What just happened?

Quite a lot just happened! We have now made all 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 doing that, it's worth trying to understand some of the lines we just entered.

Verbosity, synonyms, and "me"

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

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

put "hello world" into the text of member 1

We can perform a slightly less verbose syntax:

the text of member 1 = "hello world"

Or, we can perform a dot-syntax:

member(1).text = "hello world"

In LiveCode, there isn't a choice. What you type has to be in the form of:

put value into container

However, you do have a choice about whether to use a long version of a word, 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 the two ways of saying the same thing, with the second variation using an abbreviated form of the keywords:

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

Here, numberPressed will propagate up to a card handler that we will add (soon) and the label of me will look at the Label that you have 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 have the script and not the field itself. Still, because there is 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

Note

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

You might choose to be more verbose than is needed, just for readability reasons, and in these chapters, this is going to be the case. It is easier to tell what is going to happen by using:

put the text of me into textvariable

The following will be less verbose compared to the preceding entry, even though they are equally valid:

put me into textVariable

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

You see in the script that we typed short name of me, what's that all about? Objects in LiveCode have a lengthy description of where they are located, for example, the buttonname button of the 1234 card ID of the path/to/stack.livecode stack. In the calculator application, we need only the single word that you set as the name of the button. If we asked for name of me, it would still say "the buttonname button". 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 you need to be aware of.

Tip

Case sensitivity

If any of you use advanced LiveCode, you may notice that in some cases, I have the casing wrong. LiveCode doesn't mind what casing you have used and so, when I incorrectly said clipboarddata instead of clipboardData, it didn't matter. This feature isn't unique to LiveCode, but it is common among near-English programming languages to not demand that the user gets the casing exactly right before the command works.

Adding the card handlers

If you dared to go ahead and tried using the calculator buttons, you will see 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 make. Instead of walking you through, typing a line of code at a time, it probably would 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 the number buttons and the decimal point button, you should have this script:

on mouseup
  numberPressed the label of me
end mouseup

The on mouseUp event is triggered when you press and release the left mouse button while on the numberPressed call. This event 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

The clearPressed event will call a card script named clearPressed.

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

on mouseUp
  operatorPressed the short name of me
end mouseUp

The following script is for 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 field's case, only one line of code is being executed, 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! We will take them one at a time, with an explanation of how each one works. But first, let's see how LiveCode handles variables.

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.

Variable types in LiveCode

Generally speaking, variables are memory locations where you store values that you need to access later, but in most programming languages, you can dictate which routines have access to which variables. Less English-like languages may include the terms public, private, and protected. Things are not that different in LiveCode, but words are used that more accurately describe the region that the variable can be used in. 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 as an aside, many people would use these for performing the calculator button values instead of relying on the label of the button. Perhaps, we'll 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 discussed, these are the variables that will allow the many handlers to pass values to each other. In this case, the variables could be local, but often, you may make them global instead, thinking that a case may come up later where you need to get at the variables from outside the script you're in.

It's good to reset things when you start the app and LiveCode has an openCard event that we can pick up on. 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 their own clearPressed handler will allow us to call it at other times, not just when the card opens, and we do call it directly when we click on the C clear button. This 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 or false) variable is used to recognize whether a number button that you press should clear the display or append to the display.

All 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 comment after the handler name, is a parameter variable that stores the content that was sent to the handler. In this case, it's the label of the button that was pressed. All this routine needs to add is a character to the end of the display field, except when you are typing in a new number. That's where the newNumber Boolean variable comes in; if it is set to true, the incoming character replaces all the contents of the display field. If it's false, the character is added to the end of the field.

This is the handler to be used 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 one number, an operator, and then another number, followed by either another operator or the equals button. Now you press the operator button as there is no way to know what you're doing (since you haven't entered the next number in the calculation yet), so we have to remember the operator when we press the equals button. If the currentCommand variable doesn't already have a value, we store the display field text into a currentTotal variable, store 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 equals button.

There are most likely shorter ways to cope with the equals 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 "equals" twice in a row, we'd ignore the button press and exit the routine. For the four operators, we do the appropriate calculation. Afterwards, we store the new running total in the currentTotal variable, make sure that the newNumber Boolean is 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 in 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.

The togglesign last handler is as follows:

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 are being represented. It simply checks whether the first character is a minus or not and if it is, it deletes the character; if not, it inserts a 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 everything you may need, is located. You know what you want to do, you know how to do it, but you can't remember where that thing is located! For example:

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

Answer: 3

Getting to this section involved selecting the Edit tool from the Tools palette, clicking on the title field on card 1, and choosing Text Formatting from the Inspector palette drop-down menu. However, there is indeed a Text menu. Really, that's what we should have used!

Extending the calculator

It is possible to add more features to the simple calculator. If we consider the functions in the card script and how the buttons are named, we can start to see the processes that are involved in adding a new ability, some of these processes are as follows:

  • The calculator operator buttons are named so that the card script knows which one you clicked on.
  • When the "equals" button is pressed there is 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 add a square root symbol with Alt 251 and on Mac, with the shortcut option + v. Unfortunately, LiveCode doesn't like these as button labels! At least on Mac, when you type the character in the Inspector palette, the character immediately vanishes. One workaround would be to use the message box and type this:

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

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

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

put sqrt(10)

Now that you are armed with the given information, try to add a square root feature to the calculator.

Other interface controls

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

The video player control

LiveCode can play movies using the Player control type. These can be added to the card in several ways and then using a script command:

  • 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. In this case, a sample movie is included
  • A player along with its name can be created with the code:
    new player "player name"

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

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

The still image control

In much the same way as you just saw for the playing of video, still images can be added to a stack. All of the options shown to add a video player can be done in the same way 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://runrev.com/wp-content/themes/runrev2013/ims/runrev_logo.png"

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 have to go through 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 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 in the idle state for the button.
  6. Click on the magic wand button next to the Hilite entry and choose the highlight state image.
  7. Under Basic Properties, choose the 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.

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

Rollover buttons

When you choose an image for use, the button itself is updated. In this case, the Hilite icon has been set to the darker version of the graphic, but as shown here, the button still needs to be resized.

Rollover buttons

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 New Control. As you'll see, the list is very long!

Debugging

If you went ahead and tried out the calculator before we entered all the scripts it needed, you most likely will have seen the script debugging in action. Hopefully, you've managed to cope with what you saw, it can be overwhelming at first. This is what it would have looked like:

Debugging

Most of what you see here is the same that you'll see when you edit scripts, but if you do see the debug variation, you are actually in a paused state, which is 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. There isn't such a field, as it should be display.

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

An unexpected problem is one time that 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 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. The content displayed as you hover the cursor above a button, is it's meaning. These buttons are:

  • Continue: This will set the script that runs again
  • Stop: This stops the script from running and switches to the editor, so that you can make changes
  • Show next statement: This will show an indicator to the left of the current line
  • Step into next statement: This is used for stepping into a different handler
  • Step over next statement: This is used to go onto the next statement in the current handler without stepping in a handler mentioned on the current line
  • Step out of current handler: This is used to skip the remaining lines in a handler that you had previously stepped into and to exit to the handler that called the current one

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

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

A good starting point would be LiveCode's own set of online tutorials, which are located at http://lessons.runrev.com/.

Type in 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 by now be more familiar with the LiveCode environment.

In this chapter, we covered buttons, fields, scripts, and the stack structure to get an understanding of how they work together. We also showed several short scripts to illustrate the English-like syntax used by LiveCode while using the script window to debug a script.

We then examined other interface controls in preparation to use those in later chapters of this book.

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

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

Left arrow icon Right arrow icon

Description

The ideal reader for this book would be someone who already knows LiveCode, is interested in creating mobile apps, and wants to save the many hours it took for me to track down all of the information on how to get started! Chapter 1, LiveCode Fundamentals, will help those of you who know programming but are not familiar with LiveCode. The knowledge you've acquired should be enough for you to benefit from the remainder of the book.

What you will learn

  • Create a simple sample application and build its interface
  • Write code using a multimedia scrapbook as an example application
  • Make a "To do/reminders" application
  • Upload your final app to the app stores
  • Create a jigsaw puzzle app that takes advantage of several mobile device features
  • Make standardlooking buttons and fields and programmatically create the screen layout
  • Preview LiveCode version 8 Widget and Builder capabilities
Estimated delivery fee Deliver to Colombia

Standard delivery 10 - 13 business days

$19.95

Premium delivery 3 - 6 business days

$40.95
(Includes tracking information)

Product Details

Country selected
Publication date, Length, Edition, Language, ISBN-13
Publication date : May 29, 2015
Length: 256 pages
Edition : 1st
Language : English
ISBN-13 : 9781849699655
Category :
Tools :

What do you get with Print?

Product feature icon Instant access to your digital eBook copy whilst your Print order is Shipped
Product feature icon Paperback book shipped to your preferred address
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
OR
Modal Close icon
Payment Processing...
tick Completed

Shipping Address

Billing Address

Shipping Methods
Estimated delivery fee Deliver to Colombia

Standard delivery 10 - 13 business days

$19.95

Premium delivery 3 - 6 business days

$40.95
(Includes tracking information)

Product Details

Publication date : May 29, 2015
Length: 256 pages
Edition : 1st
Language : English
ISBN-13 : 9781849699655
Category :
Tools :

Packt Subscriptions

See our plans and pricing
Modal Close icon
$19.99 billed monthly
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Simple pricing, no contract
$199.99 billed annually
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just $5 each
Feature tick icon Exclusive print discounts
$279.99 billed in 18 months
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just $5 each
Feature tick icon Exclusive print discounts

Frequently bought together


Stars icon
Total $ 158.97
LiveCode Mobile Development Beginner's Guide
$48.99
LiveCode Mobile Development Beginner's Guide (2nd Edition)
$54.99
LiveCode Mobile Development Cookbook
$54.99
Total $ 158.97 Stars icon

Table of Contents

9 Chapters
1. LiveCode Fundamentals Chevron down icon Chevron up icon
2. Getting Started with LiveCode Mobile Chevron down icon Chevron up icon
3. Building User Interfaces Chevron down icon Chevron up icon
4. Using Remote Data and Media Chevron down icon Chevron up icon
5. Making a Jigsaw Puzzle Application Chevron down icon Chevron up icon
6. Making a Reminder Application Chevron down icon Chevron up icon
7. Deploying to Your Device Chevron down icon Chevron up icon
A. Extending LiveCode Chevron down icon Chevron up icon
Index Chevron down icon Chevron up icon

Customer reviews

Rating distribution
Full star icon Full star icon Full star icon Empty star icon Empty star icon 3
(1 Ratings)
5 star 0%
4 star 0%
3 star 100%
2 star 0%
1 star 0%
Bernie Jul 25, 2016
Full star icon Full star icon Full star icon Empty star icon Empty star icon 3
If you want a proper Livecode reference, don't bother with this.
Amazon Verified review Amazon
Get free access to Packt library with over 7500+ books and video courses for 7 days!
Start Free Trial

FAQs

What is the delivery time and cost of print book? Chevron down icon Chevron up icon

Shipping Details

USA:

'

Economy: Delivery to most addresses in the US within 10-15 business days

Premium: Trackable Delivery to most addresses in the US within 3-8 business days

UK:

Economy: Delivery to most addresses in the U.K. within 7-9 business days.
Shipments are not trackable

Premium: Trackable delivery to most addresses in the U.K. within 3-4 business days!
Add one extra business day for deliveries to Northern Ireland and Scottish Highlands and islands

EU:

Premium: Trackable delivery to most EU destinations within 4-9 business days.

Australia:

Economy: Can deliver to P. O. Boxes and private residences.
Trackable service with delivery to addresses in Australia only.
Delivery time ranges from 7-9 business days for VIC and 8-10 business days for Interstate metro
Delivery time is up to 15 business days for remote areas of WA, NT & QLD.

Premium: Delivery to addresses in Australia only
Trackable delivery to most P. O. Boxes and private residences in Australia within 4-5 days based on the distance to a destination following dispatch.

India:

Premium: Delivery to most Indian addresses within 5-6 business days

Rest of the World:

Premium: Countries in the American continent: Trackable delivery to most countries within 4-7 business days

Asia:

Premium: Delivery to most Asian addresses within 5-9 business days

Disclaimer:
All orders received before 5 PM U.K time would start printing from the next business day. So the estimated delivery times start from the next day as well. Orders received after 5 PM U.K time (in our internal systems) on a business day or anytime on the weekend will begin printing the second to next business day. For example, an order placed at 11 AM today will begin printing tomorrow, whereas an order placed at 9 PM tonight will begin printing the day after tomorrow.


Unfortunately, due to several restrictions, we are unable to ship to the following countries:

  1. Afghanistan
  2. American Samoa
  3. Belarus
  4. Brunei Darussalam
  5. Central African Republic
  6. The Democratic Republic of Congo
  7. Eritrea
  8. Guinea-bissau
  9. Iran
  10. Lebanon
  11. Libiya Arab Jamahriya
  12. Somalia
  13. Sudan
  14. Russian Federation
  15. Syrian Arab Republic
  16. Ukraine
  17. Venezuela
What is custom duty/charge? Chevron down icon Chevron up icon

Customs duty are charges levied on goods when they cross international borders. It is a tax that is imposed on imported goods. These duties are charged by special authorities and bodies created by local governments and are meant to protect local industries, economies, and businesses.

Do I have to pay customs charges for the print book order? Chevron down icon Chevron up icon

The orders shipped to the countries that are listed under EU27 will not bear custom charges. They are paid by Packt as part of the order.

List of EU27 countries: www.gov.uk/eu-eea:

A custom duty or localized taxes may be applicable on the shipment and would be charged by the recipient country outside of the EU27 which should be paid by the customer and these duties are not included in the shipping charges been charged on the order.

How do I know my custom duty charges? Chevron down icon Chevron up icon

The amount of duty payable varies greatly depending on the imported goods, the country of origin and several other factors like the total invoice amount or dimensions like weight, and other such criteria applicable in your country.

For example:

  • If you live in Mexico, and the declared value of your ordered items is over $ 50, for you to receive a package, you will have to pay additional import tax of 19% which will be $ 9.50 to the courier service.
  • Whereas if you live in Turkey, and the declared value of your ordered items is over € 22, for you to receive a package, you will have to pay additional import tax of 18% which will be € 3.96 to the courier service.
How can I cancel my order? Chevron down icon Chevron up icon

Cancellation Policy for Published Printed Books:

You can cancel any order within 1 hour of placing the order. Simply contact customercare@packt.com with your order details or payment transaction id. If your order has already started the shipment process, we will do our best to stop it. However, if it is already on the way to you then when you receive it, you can contact us at customercare@packt.com using the returns and refund process.

Please understand that Packt Publishing cannot provide refunds or cancel any order except for the cases described in our Return Policy (i.e. Packt Publishing agrees to replace your printed book because it arrives damaged or material defect in book), Packt Publishing will not accept returns.

What is your returns and refunds policy? Chevron down icon Chevron up icon

Return Policy:

We want you to be happy with your purchase from Packtpub.com. We will not hassle you with returning print books to us. If the print book you receive from us is incorrect, damaged, doesn't work or is unacceptably late, please contact Customer Relations Team on customercare@packt.com with the order number and issue details as explained below:

  1. If you ordered (eBook, Video or Print Book) incorrectly or accidentally, please contact Customer Relations Team on customercare@packt.com within one hour of placing the order and we will replace/refund you the item cost.
  2. Sadly, if your eBook or Video file is faulty or a fault occurs during the eBook or Video being made available to you, i.e. during download then you should contact Customer Relations Team within 14 days of purchase on customercare@packt.com who will be able to resolve this issue for you.
  3. You will have a choice of replacement or refund of the problem items.(damaged, defective or incorrect)
  4. Once Customer Care Team confirms that you will be refunded, you should receive the refund within 10 to 12 working days.
  5. If you are only requesting a refund of one book from a multiple order, then we will refund you the appropriate single item.
  6. Where the items were shipped under a free shipping offer, there will be no shipping costs to refund.

On the off chance your printed book arrives damaged, with book material defect, contact our Customer Relation Team on customercare@packt.com within 14 days of receipt of the book with appropriate evidence of damage and we will work with you to secure a replacement copy, if necessary. Please note that each printed book you order from us is individually made by Packt's professional book-printing partner which is on a print-on-demand basis.

What tax is charged? Chevron down icon Chevron up icon

Currently, no tax is charged on the purchase of any print book (subject to change based on the laws and regulations). A localized VAT fee is charged only to our European and UK customers on eBooks, Video and subscriptions that they buy. GST is charged to Indian customers for eBooks and video purchases.

What payment methods can I use? Chevron down icon Chevron up icon

You can pay with the following card types:

  1. Visa Debit
  2. Visa Credit
  3. MasterCard
  4. PayPal
What is the delivery time and cost of print books? Chevron down icon Chevron up icon

Shipping Details

USA:

'

Economy: Delivery to most addresses in the US within 10-15 business days

Premium: Trackable Delivery to most addresses in the US within 3-8 business days

UK:

Economy: Delivery to most addresses in the U.K. within 7-9 business days.
Shipments are not trackable

Premium: Trackable delivery to most addresses in the U.K. within 3-4 business days!
Add one extra business day for deliveries to Northern Ireland and Scottish Highlands and islands

EU:

Premium: Trackable delivery to most EU destinations within 4-9 business days.

Australia:

Economy: Can deliver to P. O. Boxes and private residences.
Trackable service with delivery to addresses in Australia only.
Delivery time ranges from 7-9 business days for VIC and 8-10 business days for Interstate metro
Delivery time is up to 15 business days for remote areas of WA, NT & QLD.

Premium: Delivery to addresses in Australia only
Trackable delivery to most P. O. Boxes and private residences in Australia within 4-5 days based on the distance to a destination following dispatch.

India:

Premium: Delivery to most Indian addresses within 5-6 business days

Rest of the World:

Premium: Countries in the American continent: Trackable delivery to most countries within 4-7 business days

Asia:

Premium: Delivery to most Asian addresses within 5-9 business days

Disclaimer:
All orders received before 5 PM U.K time would start printing from the next business day. So the estimated delivery times start from the next day as well. Orders received after 5 PM U.K time (in our internal systems) on a business day or anytime on the weekend will begin printing the second to next business day. For example, an order placed at 11 AM today will begin printing tomorrow, whereas an order placed at 9 PM tonight will begin printing the day after tomorrow.


Unfortunately, due to several restrictions, we are unable to ship to the following countries:

  1. Afghanistan
  2. American Samoa
  3. Belarus
  4. Brunei Darussalam
  5. Central African Republic
  6. The Democratic Republic of Congo
  7. Eritrea
  8. Guinea-bissau
  9. Iran
  10. Lebanon
  11. Libiya Arab Jamahriya
  12. Somalia
  13. Sudan
  14. Russian Federation
  15. Syrian Arab Republic
  16. Ukraine
  17. Venezuela