+ All Categories
Home > Documents > Corona™ SDK Language and API Referencedeveloper.coronalabs.com/demo/APIReference.pdf · Contents...

Corona™ SDK Language and API Referencedeveloper.coronalabs.com/demo/APIReference.pdf · Contents...

Date post: 09-May-2018
Category:
Upload: lenhi
View: 228 times
Download: 2 times
Share this document with a friend
68
February 3, 2010 | © 2009 Ansca Inc. All Rights Reserved. 1 Corona™ SDK Language and API Reference
Transcript

February 3, 2010 | © 2009 Ansca Inc. All Rights Reserved. 1

Corona™ SDKLanguage and API Reference

Ansca Inc. © 2009 Ansca Inc. All rights reserved.

No part of this publication may be reproduced, stored in a retrieval system, or transmitted, in any form or by any means, mechanical, electronic, photocopying, recording, or otherwise, without prior written permission of Ansca Inc., with the following exceptions: Any person is hereby authorized to store documentation on a single computer for personal use only and to print copies of documentation for personal use provided that the documentation contains Ansca’s copyright notice.

The Ansca logo is a trademark of Ansca Inc.

No licenses, express or implied, are granted with respect to any of the technology described in this document. Ansca retains all intellectual property rights associated with the technology described in this document. This document is intended to assist application developers to develop applications using Ansca software. Every effort has been made to ensure that the information in this document is accurate. Ansca is not responsible for typographical errors.

Even though Ansca has reviewed this document, ANSCA MAKES NO WARRANTY OR REPRESENTATION, EITHER EXPRESS OR IMPLIED, WITH RESPECT TO THIS DOCUMENT, ITS QUALITY, ACCURACY, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE. AS A RESULT, THIS DOCUMENT IS PROVIDED “AS IS,” AND YOU, THE READER, ARE ASSUMING THE ENTIRE RISK AS TO ITS QUALITY AND ACCURACY.

IN NO EVENT WILL ANSCA BE LIABLE FOR DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES RESULTING FROM ANY DEFECT OR INACCURACY IN THIS DOCUMENT, even if advised of the possibility of such damages.

THE WARRANTY AND REMEDIES SET FORTH ABOVE ARE EXCLUSIVE AND IN LIEU OF ALL OTHERS, ORAL OR WRITTEN, EXPRESS OR IMPLIED. No Ansca dealer, agent, or employee is authorized to make any modi"cation, extension, or addition to this warranty.

Some states do not allow the exclusion or limitation of implied warranties or liability for incidental or consequential damages, so the above limitation or exclusion may not apply to you. This warranty gives you speci"c legal rights, and you may also have other rights which vary from state to state.

Portions of chapter "Lua" and "Standard Libraries" are modi"ed from:

Lua 5.1 Reference Manualhttp://www.lua.org/manual/5.1/manual.html

which is covered under the following license:

Copyright © 1994-2008 Lua.org, PUC-Rio.

Permission is hereby granted, free of charge, to anyperson obtaining a copy of this software and associated documentation "les (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyrightnotice and this permission notice shall be included in all copies or substantial portions of the Software.

February 3, 2010 | © 2009 Ansca Inc. All Rights Reserved. 2

Contents

Introduction 8

Limitations 8

See Also 8

Lua 9

Conventions 9

Types and Values 10

Conversions between string and number 10

Objects 10

Tables 10

Variables 11

Global 11

Local 12

Table !elds (properties) 12

Expressions 12

Arithmetic Operators 12

Relational Operators 13

Logical Operators 13

Concatenation 13

Length Operator 14

Precedence 14

Properties 14

Functions 14

Plain functions 15

Object Methods 15

Dot vs Colon 15

February 3, 2010 | © 2009 Ansca Inc. All Rights Reserved. 3

Comparison with Other Languages 15

Memory Allocation 15

Common Syntax Errors and Notable Syntax Differences 16

Lua Standard Libraries 17

Basic Functions 17

Modules 20

Creating external libraries 20

Loading external libraries 20

Syntax 21

String Manipulation 22

Patterns 25

Table Manipulation 27

Mathematical Functions 28

Input and Output Facilities 30

File paths 30

Implicit (default) !le manipulation 30

Explicit !le manipulation 32

Operating System Facilities 33

Corona Core Libraries 35

Runtime 35

display 35

Creating DisplayObjects 35

Screen Properties 36

Functions 37

transition 37

easing 38

timer 39

February 3, 2010 | © 2009 Ansca Inc. All Rights Reserved. 4

media 40

Audio 40

Supported Audio Formats 40

Video 41

Supported Video Formats 41

Camera and Photo Library 41

native 42

Activity Indicator 42

Alert 43

Fonts 45

Text Input 45

Text Scrolling 46

Web Popup 46

system 47

System-de!ned directories 48

contacts 48

Display Objects 49

Common Properties 49

Common Object Methods 50

Vector Objects 51

Constructor 51

Properties 52

Object Methods 52

Images 52

Constructor 52

Text 52

Constructor 52

Properties 52

Object Methods 53

February 3, 2010 | © 2009 Ansca Inc. All Rights Reserved. 5

Groups 53

Constructor 53

Properties 53

Object Methods 53

Stage 54

Object Methods 54

Events and Listeners 55

Registering for Events 55

Examples 55

Function vs Table Listeners 56

Runtime Events 57

enterFrame 57

system 57

orientation 57

accelerometer 58

location (GPS) 58

heading (compass) 59

Targeted Events 59

completion 59

timer 60

urlRequest 60

Touch Events 60

touch 61

multitouch 61

tap 61

drag 61

Custom Events 62

Corona Internal Libraries 63

crypto 63

February 3, 2010 | © 2009 Ansca Inc. All Rights Reserved. 6

Algorithm Constants 63

socket (Networking) 64

Simple image downloading 64

Examples 64

External Libraries 65

sprite 65

Anim (“Movieclip”) 65

ui 66

Button 66

Revision History 68

February 3, 2010 | © 2009 Ansca Inc. All Rights Reserved. 7

Introduction

Ansca Corona will fundamentally change how you approach iPhone software development.

Our technology dramatically reduces these barriers to entry. We facilitate rapid development of visually rich applications. With our technology, the creative and business potential of mobile will "nally be unleashed!

We provide you with a consistent platform to build graphically-rich applications. As a developer, you will program in Lua, a simple and intuitive scripting language, and leverage Ansca’s innovative and robust API’s.

This document will discuss how to use Ansca’s API’s to maximize your productivity.

Limitations

Currently, the tools only work on Mac OS X 10.5.6 or later.

See Also

• Corona SDK Applications Programming Guide will give you the foundation to create iPhone applications using Corona.

• A highly recommended detailed and authoritative introduction to all aspects of Lua programming by Lua’s chief architect: Programming in Lua (2nd edition), by Roberto Ierusalimschy

• For an official de"nition of the language, consult Lua 5.1 Reference Manual, by R. Ierusalimschy, L. H. de Figueiredo, W. Celes. Also available online at http://www.lua.org/manual/5.1/

• Additional documentation is available at http://www.lua.org/docs.html

• A live, interactive demo of Lua is available at http://www.lua.org/demo.html. This is an excellent place to see some simple sample programs and to play with your own.

February 3, 2010 | © 2009 Ansca Inc. All Rights Reserved. 8

Lua

Corona's uses a scripting language called Lua as its programming environment.

Lua is a general-purpose programming language known for its speed and ease of use by non-programmers. The syntax is different from JavaScript but both share many common semantics.

Conventions

Names (also called identi"ers) in Lua can be any string of letters, digits, and underscores, not beginning with a digit. This coincides with the de"nition of names in most languages. (The de"nition of letter depends on the current locale: any character considered alphabetic by the current locale can be used in an identi"er.) Identi"ers are used to name variables and table "elds.

The following keywords are reserved and cannot be used as names:

and break do else elseif end false for function if in local nil not or repeat return then true until while

Lua is a case-sensitive language: and is a reserved word, but And and AND are two different, valid names. As a convention, names starting with an underscore (such as _VERSION) are reserved for use by Corona.

Comments begin anywhere with a double hyphen (--) except inside a string. They run until the end of the line. Block comments are available as well. A common trick to comment out a block is to surround it with --[[ and --]]

--[[print( 10 ) -- no action (comment)--]]

To uncomment the code, add a single hyphen at the beginning of the "rst line:

---[[print( 10 ) --> 10--]]

A numerical constant can be written with an optional decimal part and an optional decimal exponent. Lua also accepts integer hexadecimal constants, by pre"xing them with 0x. Examples of valid numerical constants are

3 3.0 3.1416 314.16e-2 0.31416E1 0xff 0x56

February 3, 2010 | © 2009 Ansca Inc. All Rights Reserved. 9

Types and Values

Lua is a dynamically typed language. Unlike other languages, you do not need to declare the type of a variable; each value implicitly carries a type.

All values in Lua are "rst-class values. This means that all values can be stored in variables, passed as arguments to other functions, and returned as results.

The basic types that you’ll deal with are:

• nil. Nil is a type with a single value, nil. By default, global variables are nil which means that they have not been assigned a value. This is analogous to null in JavaScript/ActionScript.

• boolean. The boolean type has two values, false and true. Note that in conditional expressions, e.g. if ( condition ), both false and nil evaluate as false; everything else evaluates as true.

• number. Represents real (double-precision $oating-point) numbers.

• string. Represents arrays of characters (any 8-bit character, including embedded zeroes)

• function.

• table. Tables are the fundamental data structure in Lua. They implement an associative array which is just a fancy way of saying that the array can be indexed not just by numbers, but also by any other value of the language except nil. Typically, you would use a string as an index (see Properties).

Conversions between string and number

Lua provides automatic conversion between string and number values at run time. Any arithmetic operation applied to a string tries to convert this string to a number, following the usual conversion rules. Conversely, whenever a number is used where a string is expected, the number is converted to a string, in a reasonable format. For complete control over how numbers are converted to strings, use the format function from the string library (see string.format).

Objects

Tables and functions are objects: variables do not actually contain these values, only references to them. Assignment, parameter passing, and function returns always manipulate references to such values; these operations do not imply any kind of copy.

Tables

Tables implement associative arrays, that is, arrays that can be indexed not only with numbers, but with any value (except nil). Tables can be heterogeneous; that is, they can contain values of all types (except nil). Tables are the sole data structuring mechanism in Lua; they can be used to represent ordinary arrays, symbol tables, sets, records, graphs, trees, etc. To represent records (a.k.a. properties), Lua uses the "eld name as an index. The language supports this representation by providing a.name as syntactic sugar for a["name"].

February 3, 2010 | © 2009 Ansca Inc. All Rights Reserved. 10

Like indices, the value of a table "eld can be of any type (except nil). In particular, because functions are "rst-class values, table "elds can contain functions. Thus tables can also carry methods.

You can create tables using the table constructor which is written as {}:

(1) t = {} -- create a table(2) k = "x"(3) t[k] = 3.14 -- new table entry, with key="x" and value=3.14(4) t[10] = "hi" -- new table entry, with key=10 and value="hi"(5) print( t[k] ) --> 3.14(6) print( t["x"] ) --> 3.14(7) print( t.x ) --> 3.14(8) k=10(9) print( t[k] ) --> "hi"

Note in the above example, the entry with "eld name "x" was accessed in two ways: as a property using the dot operator t.x (line 7) and as an array item using indexing t["x"] (line 6).

A common mistake is to confuse t.x with t[x]. The "rst is equivalent to t["x"], or in other words a table indexed by the string “x”. The second is a table indexed by the value of variable x.

Variables

Variables are places that store values. There are three kinds of variables in Lua: global variables, local variables, and table "elds. Any non-initialized variable is nil by default.

Global

Global variables do not need declarations. You simply assign a value to one to create it:

print( s ) --> nils = "One million dollars"print( s ) --> "One million dollars"

Global variables live as long as your application is running. You can delete a global variable by assigning nil to it. At this point, the global variable behaves as if it were never initialized:

s = nilprint( s ) --> nil

February 3, 2010 | © 2009 Ansca Inc. All Rights Reserved. 11

Local

Local variables are declared using the local statement:

x = 1 -- global variablelocal y = 10 -- local variable

Unlike global variables, local variables are visible only in the block where they are declared. The scope of the local variable begins after the declaration and ends at the end of the block.

a = 10local i = 1

while i <= 10 do local a = i*i -- different variable 'a' local to while block print( a ) --> 1, 4, 9, 16, 25, ... i = i + 1end

print( a ) --> 10 (the global 'a')

Table !elds (properties)

Table "elds are just the elements of the table themselves. You index into the array to assign the values to a "eld. When the index is a string, the "eld is known as a property (see also Properties):

t = { foo="hello" } -- create table with a single property "foo"print( t.foo ) --> "hello"t.foo = "bye" -- assign a new value to property "foo"print( t.foo ) --> "bye"t.bar = 10 --> create a new property barprint( t.bar ) --> 10print( t["bar"] ) --> 10

Expressions

Arithmetic Operators

Lua supports the usual arithmetic operators: the binary + (addition), - (subtraction), * (multiplication), / (division), % (modulo), and ^ (exponentiation); and unary - (negation). If the operands are numbers, or strings that can be converted to numbers (see Conversions between string and number), then all operations have the usual meaning. Exponentiation works for any

February 3, 2010 | © 2009 Ansca Inc. All Rights Reserved. 12

exponent. For instance, x^(-0.5) computes the inverse of the square root of x. Modulo is de"ned as

a % b == a - math.floor(a/b)*b

That is, it is the remainder of a division that rounds the quotient towards minus in"nity.

Relational Operators

The relational operators in Lua are

== ~= < > <= >=

These operators always result in false or true.

Equality (==) "rst compares the type of its operands. If the types are different, then the result is false. Otherwise, the values of the operands are compared. Numbers and strings are compared in the usual way. Objects (tables and functions) are compared by reference: two objects are considered equal only if they are the same object. Every time you create a new object (a table or function), this new object is different from any previously existing object.

The conversion rules of strings and numbers do not apply to equality comparisons. Thus, "0"==0 evaluates to false, and t[0] and t["0"] denote different entries in a table.

The operator ~= is exactly the negation of equality (==).

Logical Operators

The logical operators in Lua are and, or, and not. All logical operators consider both false and nil as false and anything else as true.

The negation operator not always returns false or true. The conjunction operator and returns its "rst argument if this value is false or nil; otherwise, and returns its second argument. The disjunction operator or returns its "rst argument if this value is different from nil and false; otherwise, or returns its second argument. Both and and or use short-cut evaluation; that is, the second operand is evaluated only if necessary. Here are some examples:

10 or 20 --> 10 10 or error() --> 10 nil or "a" --> "a" nil and 10 --> nil false and error() --> false false and nil --> false false or nil --> nil 10 and 20 --> 20

Concatenation

The string concatenation operator in Lua is denoted by two dots ('..'). If both operands are strings or numbers, then they are converted to strings.

February 3, 2010 | © 2009 Ansca Inc. All Rights Reserved. 13

Length Operator

The length operator is denoted by the unary operator #. The length of a string is its number of bytes (that is, the usual meaning of string length when each character is one byte).

The length of a table t is de"ned to be any integer index n such that t[n] is not nil and t[n+1] is nil; moreover, if t[1] is nil, n can be zero. For a regular array, with non-nil values from 1 to a given n, its length is exactly that n, the index of its last value. If the array has "holes" (that is, nil values between other non-nil values), then #t can be any of the indices that directly precedes a nil value (that is, it may consider any such nil value as the end of the array).

Precedence

Operator precedence in Lua follows the table below, from lower to higher priority:

or and < > <= >= ~= == .. + - * / % not # - (unary) ^

As usual, you can use parentheses to change the precedences of an expression. The concatenation ('..') and exponentiation ('^') operators are right associative. All other binary operators are left associative.

Properties

Many Corona API’s return objects. You are free to manipulate the documented properties of these objects just like you would on a table. You can even add your own properties provided you do not pre"x any of your custom properties with an underscore (“_”). Ansca reserves the right to use any property name that begins with an underscore.

Like most languages, all properties can be accessed via the dot (“.”) operator. It's really just a convenient way to index into a table. In other words, we can access property foo of a table t using the dot operator (t.foo) or index into it using a string (t["foo"]); the result is the same.

Functions

Because functions can be variables, a table can store them as properties. This creates allows for very $exible uses of a table. It can be used to logically group a family functions into a table, e.g. the math library. It can also be used to make a table have object methods (instance methods).

February 3, 2010 | © 2009 Ansca Inc. All Rights Reserved. 14

Plain functions

Plain functions are just what you expect. You provide some arguments as input, the function performs some task, and depending on the function, some result is returned. Most functions are stored in tables as properties. For example, to calculate the sine of 100, we would write math.sin(100). Here, math is merely a table. The property sin is the actual function.

All of the Ansca libraries such as the display library similarly group functions into tables.

Object Methods

Objects in Lua are represented by tables. Display objects (rectangles, images, etc.) and the global Runtime object are all examples of objects. Like the math library, these objects similarly store object methods (a.k.a. instance methods) as properties. One key difference, however, is syntax. You need to tell Lua that you intend this function to be called as an object method, not just a plain function. To do so, you need to use the colon (“:”) operator instead of the dot (“.”) operator. This may be slightly different than what you are used to in other languages. Compare the syntax of Javascript and Lua:

JavaScript Lua

object.translate( 10, 10 ); object:translate( 10, 10 )

Dot vs Colon

What does the colon operator do? It is actually a shortcut. In most languages, an object method call is just like a plain function call except there's a hidden "rst argument to the function that is the object itself. This hidden argument is known as this in Javascript and self in Lua. Therefore, the colon operator is merely a shortcut to save you from extra typing. You could call an object method using the dot operator if you pass the object as the "rst argument:

Object call with dot Object call with colon

object.translate( object, 10, 10 );

object:translate( 10, 10 )

Comparison with Other Languages

If you have used other scripting languages, you should have no problem adjusting to Lua.

Memory Allocation

Devices have limited memory available for use, so care must be taken to ensure that the total memory footprint of your application is kept to a minimum.

February 3, 2010 | © 2009 Ansca Inc. All Rights Reserved. 15

To help you, Lua does automatic memory management. This means you can create tables, functions, etc. but there is no function to delete them. Instead, Lua automatically deletes them via garbage collection. It can even handle cyclic data structures. So most of the burdens of memory management such as dangling pointers and memory leaks are taken care of for you.

However, it is up to you to tell Lua what to consider garbage. For example, anything stored in a global variable is not considered garbage, even if your application never uses it again. Similarly, anything stored in a table or array will not be considered garbage. In both cases, it is up to you to assign nil to these positions. This ensures that their corresponding memory will not be locked and can be freed by the garbage collector.

For display objects in the display hierarchy, the situation is slightly different. In addition to nil'ing references to a display object, you must explicitly it them from the display hierarchy before it can be considered garbage. See Remove objects from the display hierarchy.

Common Syntax Errors and Notable Syntax Differences

Some differences in syntax between Lua and other languages are worth noting because they can help avoid compiler errors:

• Semicolons. Whereas some languages require a trailing semicolon at the end of each statement (effectively a line of code), in Lua this is optional.

• Braces. You may be used to using { and } to de"ne variable scope. In Lua, you can do this by bracketing the code with do and end. Braces in Lua are interpreted as table constructors

• If then else. If you come from C, Java, Javascript, etc., a common mistake you'll make in writing if and elseif statements is forgetting to append then to the end of the if/elseif test condition. Another common mistake is inadvertently using else if (note the space) when you really mean elseif.

• Arrays. In Lua, arrays are 1-based. Technically, you can index into an array starting with 0. However, all Lua and Ansca API's assume that the "rst element of table t is t[1] not t[0].

• ? : (ternary operator). Lua does not offer the equivalent to the C ternary operator a?b:c. The Lua idiom (a and b) or c (or simply a and b or c, because and has a higher precendence than or) offers a close approximation provided b is not false. For example, the Lua equivalent to max=(x>y?x:y) would be max=(x>y and x or y). Beware that this idiom fails to work if b is false.

• Multiple return values. An unconventional but useful feature in Lua is the ability for function to return more than one result.

• Multiple Assignment. Multiple assignments offer a convenient way to swap values. The statement x,y=y,x will swap x for y and vice versa.

February 3, 2010 | © 2009 Ansca Inc. All Rights Reserved. 16

Lua Standard Libraries

Corona includes the same standard Lua libraries that are part of the Lua standard. These libraries provide useful and basic functionality. They are grouped into the following categories:

• basic library

• modules (external libraries)

• string manipulation

• table manipulation

• mathematical functions (sin, log, etc.)

• input and output

• operating system facilities

Except for the basic library, each library provides all its functions as properties of a table or as methods of its objects. This creates a logical grouping of functions and is Lua’s way of creating a namespace for different sets of functionality.

For example, to calculate the square root of 100, you would use the square root function in the math library. The function is stored as the property sqrt of the global table math so you would call the square root function like so: math.sqrt(100).

The original reference is available at http://www.lua.org/manual/5.1/manual.html#5. For security and performance reasons, several functions have been removed from the original standard Lua libraries.

Basic Functions

assert (v [, message])Issues an error when the value of its argument v is false (i.e., nil or false); otherwise, returns all its arguments. message is an error message; when absent, it defaults to "assertion failed!"

error (message [, level])Terminates the last protected function called and returns message as the error message. Function error never returns.

Usually, error adds some information about the error position at the beginning of the message. The level argument speci"es how to get the error position. With level 1 (the default), the error position is where the error function was called. Level 2 points the error to where the function that called error was called; and so on. Passing a level 0 avoids the addition of error position information to the message.

_GA global variable (not a function) that holds the global environment (that is, _G._G = _G). Lua itself does not use this variable; changing its value does not affect any environment, nor vice-versa. (Use setfenv to change environments.)

February 3, 2010 | © 2009 Ansca Inc. All Rights Reserved. 17

getfenv ([f])Returns the current environment in use by the function. f can be a Lua function or a number that speci"es the function at that stack level: Level 1 is the function calling getfenv. If the given function is not a Lua function, or if f is 0, getfenv returns the global environment. The default for f is 1.

getmetatable (object)If object does not have a metatable, returns nil. Otherwise, if the object's metatable has a "__metatable" "eld, returns the associated value. Otherwise, returns the metatable of the given object.

ipairs (t)Returns three values: an iterator function, the table t, and 0, so that the construction

for i,v in ipairs(t) do body end

will iterate over the pairs (1,t[1]), (2,t[2]), ..., up to the "rst integer key absent from the table.

next (table [, index])Allows a program to traverse all "elds of a table. Its "rst argument is a table and its second argument is an index in this table. next returns the next index of the table and its associated value. When called with nil as its second argument, next returns an initial index and its associated value. When called with the last index, or with nil in an empty table, next returns nil. If the second argument is absent, then it is interpreted as nil. In particular, you can use next(t) to check whether a table is empty.

The order in which the indices are enumerated is not speci"ed, even for numeric indices. (To traverse a table in numeric order, use a numerical for or the ipairs function.)

The behavior of next is unde"ned if, during the traversal, you assign any value to a non-existent "eld in the table. You may however modify existing "elds. In particular, you may clear existing "elds.

pairs (t)Returns three values: the next function, the table t, and nil, so that the construction

for k,v in pairs(t) do body end

will iterate over all key–value pairs of table t.

See function next for the caveats of modifying the table during its traversal.

pcall (f, arg1, ...)Calls function f with the given arguments in protected mode. This means that any error inside f is not propagated; instead, pcall catches the error and returns a status code. Its "rst result is the status code (a boolean), which is false if the call succeeds without errors. In such case, pcall also returns all results from the call, after this "rst result. In case of any error, pcall returns false plus the error message.

print (...)Receives any number of arguments, and prints their values to stdout, using the tostring function to convert them to strings. print is not intended for formatted output, but only as a quick way to show a value, typically for debugging. For formatted output, use string.format.

February 3, 2010 | © 2009 Ansca Inc. All Rights Reserved. 18

rawequal (v1, v2)Checks whether v1 is equal to v2, without invoking any metamethod. Returns a boolean.

rawget (table, index)Gets the real value of table[index], without invoking any metamethod. table must be a table; index may be any value.

rawset (table, index, value)Sets the real value of table[index] to value, without invoking any metamethod. table must be a table, index any value different from nil, and value any Lua value.

This function returns table.

select (index, ...)If index is a number, returns all arguments after argument number index. Otherwise, index must be the string "#", and select returns the total number of extra arguments it received.

setfenv (f, table)Sets the environment to be used by the given function. f can be a Lua function or a number that speci"es the function at that stack level: Level 1 is the function calling setfenv. setfenv returns the given function.

As a special case, when f is 0 setfenv changes the environment of the running thread. In this case, setfenv returns no values.

setmetatable (table, metatable)Sets the metatable for the given table. (You cannot change the metatable of other types from Lua, only from C.) If metatable is nil, removes the metatable of the given table. If the original metatable has a "__metatable" "eld, raises an error.

This function returns table.

tonumber (e [, base])Tries to convert its argument to a number. If the argument is already a number or a string convertible to a number, then tonumber returns this number; otherwise, it returns nil.

An optional argument speci"es the base to interpret the numeral. The base may be any integer between 2 and 36, inclusive. In bases above 10, the letter 'A' (in either upper or lower case) represents 10, 'B' represents 11, and so forth, with 'Z' representing 35. In base 10 (the default), the number can have a decimal part, as well as an optional exponent part (see §2.1). In other bases, only unsigned integers are accepted.

tostring (e)Receives an argument of any type and converts it to a string in a reasonable format. For complete control of how numbers are converted, use string.format.

If the metatable of e has a "__tostring" "eld, then tostring calls the corresponding value with e as argument, and uses the result of the call as its result.

type (v)Returns the type of its only argument, coded as a string. The possible results of this function are "nil" (a string, not the value nil), "number", "string", "boolean", "table", "function", "thread", and "userdata".

February 3, 2010 | © 2009 Ansca Inc. All Rights Reserved. 19

unpack (list [, i [, j]])Returns the elements from the given table. This function is equivalent to

return list[i], list[i+1], ..., list[j]

except that the above code can be written only for a "xed number of elements. By default, i is 1 and j is the length of the list, as de"ned by the length operator (see §2.5.5).

Modules

Corona supports Lua’s module functionality for creating and loading external libraries. Currently, two example libraries are shipped with the SDK: “ui.lua” (for creating rollover buttons) and “sprite.lua” (for creating animated sprites, or “movieclips”).

These libraries can be found in the sample projects “Button” and “Movieclip”, located in the Sample Code directory of the SDK. To use them in your own projects, copy them to your project directory.

You can also create Lua modules of your own, which is helpful for organizing large projects into multiple "les, or creating reusable code libraries for future projects.

Creating external libraries

The easiest way to create a module is to use the following format, and save it to the same directory as your project’s main.lua "le:

module(..., package.seeall)

-- Declare the functions you want in your modulefunction hello() print ("Hello, module")end

The "rst line should be entered as shown here, including the three dots. Modules should be saved with a “.lua” "le extension: for example, “testlib.lua”.

Loading external libraries

To load a module from your project directory, use require (modname) at the beginning of your main.lua "le. The functions within the module will then be available using the format modname.functionname().

You can optimize your main.lua by caching library functions as local variables:

February 3, 2010 | © 2009 Ansca Inc. All Rights Reserved. 20

-- Load external library (should be in the same folder as main.lua)local testlib = require("testlib")

-- Now the functions in "testlib.lua" are available here:

-- call the testlib library function hello(). The "slow" waytestlib.hello()

-- cache same function, if you call more than oncelocal hello = testlib.hello()

-- now all future invocations are "fast"hello()

Syntax

module (name [, ···])Creates a module. If there is a table in package.loaded[name], this table is the module. Otherwise, if there is a global table t with the given name, this table is the module. Otherwise creates a new table t and sets it as the value of the global name and the value of package.loaded[name]. This function also initializes t._NAME with the given name, t._M with the module (t itself ), and t._PACKAGE with the package name (the full module name minus last component; see below). Finally, module sets t as the new environment of the current function and the new value of package.loaded[name], so that require returns t.

This function may receive optional options after the module name, where each option is a function to be applied over the module.

require (modname)Loads the given module. The function starts by looking into the package.loaded table to determine whether modname is already loaded. If it is, then require returns the value stored at package.loaded[modname]. Otherwise, it tries to "nd a loader for the module.

To "nd a loader, require is guided by the package.loaders array. By changing this array, we can change how require looks for a module. The following explanation is based on the default con"guration for package.loaders.

First, require queries package.preload[modname]. If it has a value, this value (which should be a function) is the loader. Otherwise require searches for a Lua loader using the path stored in package.path. If that also fails, it tries an all-in-one loader (see package.loaders).

Once a loader is found, require calls the loader with a single argument, modname. If the loader returns any value, require assigns the returned value to package.loaded[modname]. If the loader returns no value and has not assigned any value to package.loaded[modname], then require assigns true to this entry. In any case, require returns the "nal value of package.loaded[modname].

If there is any error loading or running the module, or if it cannot "nd any loader for the module, then require signals an error.

February 3, 2010 | © 2009 Ansca Inc. All Rights Reserved. 21

package.loadedA table used by require to control which modules are already loaded. When you require a module modname and package.loaded[modname] is not false, require simply returns the value stored there.

package.loadersA table used by require to control how to load modules.

Each entry in this table is a searcher function. When looking for a module, require calls each of these searchers in ascending order, with the module name (the argument given to require) as its sole parameter. The function may return another function (the module loader) or a string explaining why it did not "nd that module (or nil if it has nothing to say).

When running in the simulator, the searcher looks for Lua "les that can serve as Lua libraries. These Lua "les must be in the same directory as your main.lua "le. As long as they are in the same directory as your main.lua "le, they will be packaged for you during device builds.

package.seeall (module)Sets a metatable for module with its __index "eld referring to the global environment, so that this module inherits values from the global environment. To be used as an option to function module.

String Manipulation

This library provides generic functions for string manipulation, such as "nding and extracting substrings, and pattern matching. When indexing a string in Lua, the "rst character is at position 1 (not at 0, as in C). Indices are allowed to be negative and are interpreted as indexing backwards, from the end of the string. Thus, the last character is at position -1, and so on.

The string library provides all its functions inside the table string. It also sets a metatable for strings where the __index "eld points to the string table. Therefore, you can use the string functions in object-oriented style. For instance, string.byte(s, i) can be written as s:byte(i).

The string library assumes one-byte character encodings.

string.byte (s [, i [, j]])Returns the internal numerical codes of the characters s[i], s[i+1], ..., s[j]. The default value for i is 1; the default value for j is i.

Note that numerical codes are not necessarily portable across platforms.

string.char (...)Receives zero or more integers. Returns a string with length equal to the number of arguments, in which each character has the internal numerical code equal to its corresponding argument.

Note that numerical codes are not necessarily portable across platforms.

string.!nd (s, pattern [, init [, plain]])Looks for the "rst match of pattern in the string s. If it "nds a match, then "nd returns the indices of s where this occurrence starts and ends; otherwise, it returns nil. A third, optional numerical argument init speci"es where to start the search; its default value is 1 and can be

February 3, 2010 | © 2009 Ansca Inc. All Rights Reserved. 22

negative. A value of false as a fourth, optional argument plain turns off the pattern matching facilities, so the function does a plain ""nd substring" operation, with no characters in pattern being considered "magic". Note that if plain is given, then init must be given as well.

If the pattern has captures, then in a successful match the captured values are also returned, after the two indices.

string.format (formatstring, ...)Returns a formatted version of its variable number of arguments following the description given in its "rst argument (which must be a string). The format string follows the same rules as the printf family of standard C functions. The only differences are that the options/modi"ers *, l, L, n, p, and h are not supported and that there is an extra option, q. The q option formats a string in a form suitable to be safely read back by the Lua interpreter: the string is written between double quotes, and all double quotes, newlines, embedded zeros, and backslashes in the string are correctly escaped when written. For instance, the call

string.format('%q', 'a string with "quotes" and \n new line')

will produce the string:

"a string with \"quotes\" and \

new line"

The options c, d, E, e, f, g, G, i, o, u, X, and x all expect a number as argument, whereas q and s expect a string.

This function does not accept string values containing embedded zeros, except as arguments to the q option.

string.gmatch (s, pattern)Returns an iterator function that, each time it is called, returns the next captures from pattern over string s. If pattern speci"es no captures, then the whole match is produced in each call.

As an example, the following loop

s = "hello world from Lua"

for w in string.gmatch(s, "%a+") do

print(w)

end

will iterate over all the words from string s, printing one per line. The next example collects all pairs key=value from the given string into a table:

t = {}

s = "from=world, to=Lua"

for k, v in string.gmatch(s, "(%w+)=(%w+)") do

t[k] = v

end

February 3, 2010 | © 2009 Ansca Inc. All Rights Reserved. 23

For this function, a '^' at the start of a pattern does not work as an anchor, as this would prevent the iteration.

string.gsub (s, pattern, repl [, n])Returns a copy of s in which all (or the "rst n, if given) occurrences of the pattern have been replaced by a replacement string speci"ed by repl, which can be a string, a table, or a function. gsub also returns, as its second value, the total number of matches that occurred.

If repl is a string, then its value is used for replacement. The character % works as an escape character: any sequence in repl of the form %n, with n between 1 and 9, stands for the value of the n-th captured substring (see below). The sequence %0 stands for the whole match. The sequence %% stands for a single %.

If repl is a table, then the table is queried for every match, using the "rst capture as the key; if the pattern speci"es no captures, then the whole match is used as the key.

If repl is a function, then this function is called every time a match occurs, with all captured substrings passed as arguments, in order; if the pattern speci"es no captures, then the whole match is passed as a sole argument.

If the value returned by the table query or by the function call is a string or a number, then it is used as the replacement string; otherwise, if it is false or nil, then there is no replacement (that is, the original match is kept in the string).

Here are some examples:

x = string.gsub("hello world", "(%w+)", "%1 %1") --> x="hello hello world world" x = string.gsub("hello world", "%w+", "%0 %0", 1) --> x="hello hello world" x = string.gsub("hello world from Lua", "(%w+)%s*(%w+)", "%2 %1") --> x="world hello Lua from" x = string.gsub("home = $HOME, user = $USER", "%$(%w+)", os.getenv) --> x="home = /home/roberto, user = roberto" x = string.gsub("4+5 = $return 4+5$", "%$(.-)%$", function (s) return loadstring(s)() end) --> x="4+5 = 9" local t = {name="lua", version="5.1"} x = string.gsub("$name-$version.tar.gz", "%$(%w+)", t) --> x="lua-5.1.tar.gz"

string.len (s)Receives a string and returns its length. The empty string "" has length 0. Embedded zeros are counted, so "a\000bc\000" has length 5.

February 3, 2010 | © 2009 Ansca Inc. All Rights Reserved. 24

string.lower (s)Receives a string and returns a copy of this string with all uppercase letters changed to lowercase. All other characters are left unchanged. The de"nition of what an uppercase letter is depends on the current locale.

string.match (s, pattern [, init])Looks for the "rst match of pattern in the string s. If it "nds one, then match returns the captures from the pattern; otherwise it returns nil. If pattern speci"es no captures, then the whole match is returned. A third, optional numerical argument init speci"es where to start the search; its default value is 1 and can be negative.

string.rep (s, n)Returns a string that is the concatenation of n copies of the string s.

string.reverse (s)Returns a string that is the string s reversed.

string.sub (s, i [, j])Returns the substring of s that starts at i and continues until j; i and j can be negative. If j is absent, then it is assumed to be equal to -1 (which is the same as the string length). In particular, the call string.sub(s,1,j) returns a pre"x of s with length j, and string.sub(s, -i) returns a suffix of s with length i.

string.upper (s)Receives a string and returns a copy of this string with all lowercase letters changed to uppercase. All other characters are left unchanged. The de"nition of what a lowercase letter is depends on the current locale.

Patterns

Character Class:

A character class is used to represent a set of characters. The following combinations are allowed in describing a character class:

x: (where x is not one of the magic characters ^$()%.[]*+-?) represents the character x itself.

.: (a dot) represents all characters.

%a: represents all letters.

%c: represents all control characters.

%d: represents all digits.

%l: represents all lowercase letters.

%p: represents all punctuation characters.

%s: represents all space characters.

%u: represents all uppercase letters.

%w: represents all alphanumeric characters.

February 3, 2010 | © 2009 Ansca Inc. All Rights Reserved. 25

%x: represents all hexadecimal digits.

%z: represents the character with representation 0.

%x: (where x is any non-alphanumeric character) represents the character x. This is the standard way to escape the magic characters. Any punctuation character (even the non magic) can be preceded by a '%' when used to represent itself in a pattern.

[set]: represents the class which is the union of all characters in set. A range of characters can be speci"ed by separating the end characters of the range with a '-'. All classes %x described above can also be used as components in set. All other characters in set represent themselves. For example, [%w_] (or [_%w]) represents all alphanumeric characters plus the underscore, [0-7] represents the octal digits, and [0-7%l%-] represents the octal digits plus the lowercase letters plus the '-' character. The interaction between ranges and classes is not de"ned. Therefore, patterns like [%a-z] or [a-%%] have no meaning.

[^set]: represents the complement of set, where set is interpreted as above.

For all classes represented by single letters (%a, %c, etc.), the corresponding uppercase letter represents the complement of the class. For instance, %S represents all non-space characters.

The de"nitions of letter, space, and other character groups depend on the current locale. In particular, the class [a-z] may not be equivalent to %l.

Pattern Item:A pattern item can be

• a single character class, which matches any single character in the class;

• a single character class followed by '*', which matches 0 or more repetitions of characters in the class. These repetition items will always match the longest possible sequence;

• a single character class followed by '+', which matches 1 or more repetitions of characters in the class. These repetition items will always match the longest possible sequence;

• a single character class followed by '-', which also matches 0 or more repetitions of characters in the class. Unlike '*', these repetition items will always match the shortest possible sequence;

• a single character class followed by '?', which matches 0 or 1 occurrence of a character in the class;

• %n, for n between 1 and 9; such item matches a substring equal to the n-th captured string (see below);

• %bxy, where x and y are two distinct characters; such item matches strings that start with x, end with y, and where the x and y are balanced. This means that, if one reads the string from left to right, counting +1 for an x and -1 for a y, the ending y is the "rst y where the count reaches 0. For instance, the item %b() matches expressions with balanced parentheses.

Pattern:A pattern is a sequence of pattern items. A '^' at the beginning of a pattern anchors the match at the beginning of the subject string. A '$' at the end of a pattern anchors the match at the end of the subject string. At other positions, '^' and '$' have no special meaning and represent themselves.

February 3, 2010 | © 2009 Ansca Inc. All Rights Reserved. 26

Captures:A pattern can contain sub-patterns enclosed in parentheses; they describe captures. When a match succeeds, the substrings of the subject string that match captures are stored (captured) for future use. Captures are numbered according to their left parentheses. For instance, in the pattern "(a*(.)%w(%s*))", the part of the string matching "a*(.)%w(%s*)" is stored as the "rst capture (and therefore has number 1); the character matching "." is captured with number 2, and the part matching "%s*" has number 3.

As a special case, the empty capture () captures the current string position (a number). For instance, if we apply the pattern "()aa()" on the string "$aaap", there will be two captures: 3 and 5.

A pattern cannot contain embedded zeros. Use %z instead.

Table Manipulation

This library provides generic functions for table manipulation. It provides all its functions inside the table table.

Most functions in the table library assume that the table represents an array or a list. For these functions, when we talk about the "length" of a table we mean the result of the length operator.

table.concat (table [, sep [, i [, j]]])Given an array where all elements are strings or numbers, returns table[i]..sep..table[i+1] ... sep..table[j]. The default value for sep is the empty string, the default for i is 1, and the default for j is the length of the table. If i is greater than j, returns the empty string.

table.insert (table, [pos,] value)Inserts element value at position pos in table, shifting up other elements to open space, if necessary. The default value for pos is n+1, where n is the length of the table, so that a call table.insert(t,x) inserts x at the end of table t; however, if you are inserting at the end of the table, it is faster to use the length operator: t[#t + 1] = x.

table.maxn (table)Returns the largest positive numerical index of the given table, or zero if the table has no positive numerical indices. (To do its job this function does a linear traversal of the whole table.)

table.remove (table [, pos])Removes from table the element at position pos, shifting down other elements to close the space, if necessary. Returns the value of the removed element. The default value for pos is n, where n is the length of the table, so that a call table.remove(t) removes the last element of table t.

table.sort (table [, comp])Sorts table elements in a given order, in-place, from table[1] to table[n], where n is the length of the table. If comp is given, then it must be a function that receives two table elements, and returns false when the "rst is less than the second (so that not comp(a[i+1],a[i]) will be false after the sort). If comp is not given, then the standard Lua operator < is used instead.

February 3, 2010 | © 2009 Ansca Inc. All Rights Reserved. 27

The sort algorithm is not stable; that is, elements considered equal by the given order may have their relative positions changed by the sort.

Mathematical Functions

This library is an interface to the standard C math library. It provides all its functions inside the table math.

math.abs (x)Returns the absolute value of x.

math.acos (x)Returns the arc cosine of x (in radians).

math.asin (x)Returns the arc sine of x (in radians).

math.atan (x)Returns the arc tangent of x (in radians).

math.atan2 (y, x)Returns the arc tangent of y/x (in radians), but uses the signs of both parameters to "nd the quadrant of the result. (It also handles correctly the case of x being zero.)

math.ceil (x)Returns the smallest integer larger than or equal to x.

math.cos (x)Returns the cosine of x (assumed to be in radians).

math.cosh (x)Returns the hyperbolic cosine of x.

math.deg (x)Returns the angle x (given in radians) in degrees.

math.exp (x)Returns the value ex.

math."oor (x)Returns the largest integer smaller than or equal to x.

math.fmod (x, y)Returns the remainder of the division of x by y that rounds the quotient towards zero.

math.frexp (x)Returns m and e such that x = m2e, e is an integer and the absolute value of m is in the range [0.5, 1) (or zero when x is zero).

math.hugeThe value HUGE_VAL, a value larger than or equal to any other numerical value.

math.ldexp (m, e)Returns m2e (e should be an integer).

February 3, 2010 | © 2009 Ansca Inc. All Rights Reserved. 28

math.log (x)Returns the natural logarithm of x.

math.log10 (x)Returns the base-10 logarithm of x.

math.max (x, ...)Returns the maximum value among its arguments.

math.min (x, ...)Returns the minimum value among its arguments.

math.modf (x)Returns two numbers, the integral part of x and the fractional part of x.

math.piThe value of pi.

math.pow (x, y)Returns xy. (You can also use the expression x^y to compute this value.)

math.rad (x)Returns the angle x (given in degrees) in radians.

math.random ([m [, n]])This function is an interface to the simple pseudo-random generator function rand provided by ANSI C. (No guarantees can be given for its statistical properties.)

When called without arguments, returns a uniform pseudo-random real number in the range [0,1). When called with an integer number m, math.random returns a uniform pseudo-random integer in the range [1, m]. When called with two integer numbers m and n, math.random returns a uniform pseudo-random integer in the range [m, n].

math.randomseed (x)Sets x as the "seed" for the pseudo-random generator: equal seeds produce equal sequences of numbers.

math.sin (x)Returns the sine of x (assumed to be in radians).

math.sinh (x)Returns the hyperbolic sine of x.

math.sqrt (x)Returns the square root of x. (You can also use the expression x^0.5 to compute this value.)

math.tan (x)Returns the tangent of x (assumed to be in radians).

math.tanh (x)Returns the hyperbolic tangent of x.

February 3, 2010 | © 2009 Ansca Inc. All Rights Reserved. 29

Input and Output Facilities

The I/O library provides two different styles for "le manipulation. The "rst one implicitly operates on a default "le object; that is, there are operations to set a default input "le and a default output "le, and all input/output operations are over these default "les. The second style uses explicit "le objects.

When using implicit "le descriptors, all operations are supplied by table io. When using explicit "le descriptors, the operation io.open returns a "le descriptor and then all operations are supplied as methods of the "le descriptor.

The table io also provides three prede"ned "le descriptors with their usual meanings from C: io.stdin, io.stdout, and io.stderr. The I/O library never closes these "les.

Unless otherwise stated, all I/O functions return nil on failure (plus an error message as a second result and a system-dependent error code as a third result) and some value different from nil on success.

File paths

For security reasons, you can only open "les in your application's sandbox. The io library requires you to supply paths to these "les. To do so, you use system.pathForFile.

Here's an example of how to open an existing "le or create one if it does not already exist:

local path = system.pathForFile( "data.txt", system.DocumentsDirectory )

-- io.open opens a file at path. returns nil if no file foundlocal file = io.open( path, "r" )if file then -- read all contents of file into a string local contents = file:read( "*a" ) print( "Contents of " .. path .. "\n" .. contents ) io.close( file )else -- create file b/c it doesn't exist yet file = io.open( path, "w" ) local numbers = {1,2,3,4,5,6,7,8,9} file:write( "Feed me data!\n", numbers[1], numbers[2], "\n" ) for _,v in ipairs( numbers ) do file:write( v, " " ) end file:write( "\nNo more data\n" ) io.close( file )end

Implicit (default) !le manipulation

io.close ([!le])Equivalent to "le:close(). Without a "le, closes the default output "le.

February 3, 2010 | © 2009 Ansca Inc. All Rights Reserved. 30

io."ush ()Equivalent to "le:$ush over the default output "le.

io.input ([!le])When called with a "le name, it opens the named "le (in text mode), and sets its handle as the default input "le. When called with a "le handle, it simply sets this "le handle as the default input "le. When called without parameters, it returns the current default input "le.

In case of errors this function raises the error, instead of returning an error code.

io.lines ([!lename])Opens the given "le name in read mode and returns an iterator function that, each time it is called, returns a new line from the "le. Therefore, the construction

for line in io.lines(filename) do body end

will iterate over all lines of the "le. When the iterator function detects the end of "le, it returns nil (to "nish the loop) and automatically closes the "le.

The call io.lines() (with no "le name) is equivalent to io.input():lines(); that is, it iterates over the lines of the default input "le. In this case it does not close the "le when the loop ends.

io.open (!lename [, mode])This function opens a "le, in the mode speci"ed in the string mode. It returns a new "le handle, or, in case of errors, nil plus an error message.

The mode string can be any of the following:

"r": read mode (the default);

"w": write mode;

"a": append mode;

"r+": update mode, all previous data is preserved;

"w+": update mode, all previous data is erased;

"a+": append update mode, previous data is preserved, writing is only allowed at the end of "le.

The mode string can also have a 'b' at the end, which is needed in some systems to open the "le in binary mode. This string is exactly what is used in the standard C function fopen.

io.output ([!le])Similar to io.input, but operates over the default output "le.

io.popen (prog [, mode])Starts program prog in a separated process and returns a "le handle that you can use to read data from this program (if mode is "r", the default) or to write data to this program (if mode is "w").

This function is system dependent and is not available on all platforms.

io.read (...)Equivalent to io.input():read.

February 3, 2010 | © 2009 Ansca Inc. All Rights Reserved. 31

io.tmp!le ()Returns a handle for a temporary "le. This "le is opened in update mode and it is automatically removed when the program ends.

io.type (obj)Checks whether obj is a valid "le handle. Returns the string ""le" if obj is an open "le handle, "closed "le" if obj is a closed "le handle, or nil if obj is not a "le handle.

io.write (...)Equivalent to io.output():write.

Explicit !le manipulation

You create a "le object using the object returned by the function io.open. Note the use of colon ':' indicating that all operations are on the object (see Object Methods) .

!le:close ()Closes "le. Note that "les are automatically closed when their handles are garbage collected, but that takes an unpredictable amount of time to happen.

!le:"ush ()Saves any written data to "le.

!le:lines ()Returns an iterator function that, each time it is called, returns a new line from the "le. Therefore, the construction

for line in "le:lines() do body end

will iterate over all lines of the "le. (Unlike io.lines, this function does not close the "le when the loop ends.)

!le:read (...)Reads the "le "le, according to the given formats, which specify what to read. For each format, the function returns a string (or a number) with the characters read, or nil if it cannot read data with the speci"ed format. When called without formats, it uses a default format that reads the entire next line (see below).

The available formats are

"*n": reads a number; this is the only format that returns a number instead of a string.

"*a": reads the whole "le, starting at the current position. On end of "le, it returns the empty string.

"*l": reads the next line (skipping the end of line), returning nil on end of "le. This is the default format.

number: reads a string with up to this number of characters, returning nil on end of "le. If number is zero, it reads nothing and returns an empty string, or nil on end of "le.

!le:seek ([whence] [, offset])Sets and gets the "le position, measured from the beginning of the "le, to the position given by offset plus a base speci"ed by the string whence, as follows:

February 3, 2010 | © 2009 Ansca Inc. All Rights Reserved. 32

"set": base is position 0 (beginning of the "le);

"cur": base is current position;

"end": base is end of "le;

In case of success, function seek returns the "nal "le position, measured in bytes from the beginning of the "le. If this function fails, it returns nil, plus a string describing the error.

The default value for whence is "cur", and for offset is 0. Therefore, the call "le:seek() returns the current "le position, without changing it; the call "le:seek("set") sets the position to the beginning of the "le (and returns 0); and the call "le:seek("end") sets the position to the end of the "le, and returns its size.

!le:setvbuf (mode [, size])Sets the buffering mode for an output "le. There are three available modes:

"no": no buffering; the result of any output operation appears immediately.

"full": full buffering; output operation is performed only when the buffer is full (or when you explicitly $ush the "le (see io.$ush)).

"line": line buffering; output is buffered until a newline is output or there is any input from some special "les (such as a terminal device).

For the last two cases, size speci"es the size of the buffer, in bytes. The default is an appropriate size.

!le:write (...)Writes the value of each of its arguments to the "le. The arguments must be strings or numbers. To write other values, use tostring or string.format before write.

Operating System Facilities

This library is implemented through table os.

os.clock ()Returns an approximation of the amount in seconds of CPU time used by the program.

os.date ([format [, time]])Returns a string or a table containing date and time, formatted according to the given string format.

If the time argument is present, this is the time to be formatted (see the os.time function for a description of this value). Otherwise, date formats the current time.

If format starts with '!', then the date is formatted in Coordinated Universal Time. After this optional character, if format is the string "*t", then date returns a table with the following "elds: year (four digits), month (1--12), day (1--31), hour (0--23), min (0--59), sec (0--61), wday (weekday, Sunday is 1), yday (day of the year), and isdst (daylight saving $ag, a boolean).

If format is not "*t", then date returns the date as a string, formatted according to the same rules as the C function strftime.

February 3, 2010 | © 2009 Ansca Inc. All Rights Reserved. 33

When called without arguments, date returns a reasonable date and time representation that depends on the host system and on the current locale (that is, os.date() is equivalent to os.date("%c")).

os.difftime (t2, t1)Returns the number of seconds from time t1 to time t2. In POSIX, Windows, and some other systems, this value is exactly t2-t1.

os.exit ([code])Calls the C function exit, with an optional code, to terminate the host program. The default value for code is the success code.

os.remove (!lename)Deletes the "le or directory with the given name. Directories must be empty to be removed. If this function fails, it returns nil, plus a string describing the error.

os.rename (oldname, newname)Renames "le or directory named oldname to newname. If this function fails, it returns nil, plus a string describing the error.

os.time ([table])Returns the current time when called without arguments, or a time representing the date and time speci"ed by the given table. This table must have "elds year, month, and day, and may have "elds hour, min, sec, and isdst (for a description of these "elds, see the os.date function).

The returned value is a number, whose meaning depends on your system. In POSIX, Windows, and some other systems, this number counts the number of seconds since some given start time (the "epoch"). In other systems, the meaning is not speci"ed, and the number returned by time can be used only as an argument to date and difftime.

February 3, 2010 | © 2009 Ansca Inc. All Rights Reserved. 34

Corona Core Libraries

Corona adds its own set of libraries on top of the standard Lua libraries. These libraries enable you to create applications. Some libraries are built-in whereas others must be explicitly loaded.

The following are Corona’s core libraries. These are built-in and loaded automatically when the application launches:

• display provides all routines for creating display objects.

• transition simpli"es the animation of display objects, simplifying the process of creating basic tweens.

• easing is a collection of interpolation functions that can be used in conjunction with the transition library.

• timer provides rudimentary timing functions such as delayed invocation.

• media provides access to the multimedia capabilities of the device.

• native provides access to native interface elements that may vary in appearance and size across devices.

• system is a misc collection of system level features.

Just like the standard Lua libraries, you can access them at the global scope; you do not have to explicitly load them using require.

Runtime

A global Runtime object exists for the lifetime of your application. It is the object you use to register for Runtime events. For more information on events and listeners, see Registering for Events.

display

The display library contains all functionality related to drawing that occurs on the screen. More information on concepts and drawing to the screen is available in the Graphics and Drawing chapter of the Corona SDK Applications Programming Guide.

This library is organized into functions that allow you to draw objects, properties of the screen itself, and useful utility functions.

Creating DisplayObjects

Everything you draw on the screen is a DisplayObject. This section only explains the functions for creating these objects, so be sure to check out the Display Objects chapter to learn more about display objects.

February 3, 2010 | © 2009 Ansca Inc. All Rights Reserved. 35

As explained in the Display Objects chapter, DisplayObjects share some common properties and methods. In addition, there are speci"c types of DisplayObjects (including vector objects, groups, text, and images) that have additional properties and methods.

display.newCircle( xCenter, yCenter, radius )Creates a circle with radius radius centered at (xCenter, yCenter); returns a VectorObject representing it. The local origin is at the center of the circle; the reference point is initialized to this local origin. By default, there is no "ll or stroke color.

display.newGroup() Creates a group in which you can add and remove child display objects; returns a GroupObject representing it. Initially, there are no children in a group. The local origin is at the parent's origin; the reference point is initialized to this local origin.

display.newImage( !lename [, baseDirectory] [, left, top] )Returns an image object. It loads the image data from filename and by default looks in the system.ResourceDirectory for that "le. If you specify the argument baseDirectory it will look in that directory instead (see system.pathForFile for valid values of baseDirectory).

You can specify that the image's top-left corner be located at the coordinate (left, top); if you don't supply both coordinates, the image will be centered about its local origin.

The local origin is at the center of the image; the reference point is initialized to this point.

display.newRect( left, top, width, height ) Creates a rectangle with dimensions width by height with the top-left corner at (left, top); returns a VectorObject representing it. The local origin is at the center of the rectangle; the reference point is initialized to this local origin. By default, there is no "ll or stroke color.

display.newRoundedRect( left, top, width, height, cornerRadius )Creates a width by height rounded rectangle with the top-left corner at (left, top); returns a VectorObject representing it. The corners are rounded by quarter circles of radius cornerRadius. The local origin is at the center of the rectangle; the reference point is initialized to this local origin. By default, there is no "ll or stroke color.

display.newText( string, x, y, font, size ) Creates a text object with its top-left corner at (x, y); returns a TextObject representing it. The font argument speci"es the font to use. The local origin is at the center of the text; the reference point is initialized to this local origin. By default, there is no text color.

Screen Properties

display.stageWidthA read-only property representing the width of the screen in pixels

display.stageHeightA read-only property representing the height of the screen in pixels

display.statusBarHeight A read-only property representing the height of the status bar in pixels

February 3, 2010 | © 2009 Ansca Inc. All Rights Reserved. 36

Functions

display.captureScreen( saveToAlbum ) Captures the contents of the screen and returns it as an image object positioned so that the top-left of the screen is at the origin. If saveToAlbum is false, then it adds the image to your device's album; on the simulator, it saves to the desktop.

display.save( displayObject, !lename [, baseDirectory] ) Renders the display object referenced by displayObject into a JPEG image and saves it in filename. The display object must currently be in the display hierarchy; otherwise no image is saved. If the display object is a group object, then all children are rendered. The argument baseDirectory is optional. It can be either system.DocumentsDirectory (the default) or system.TemporaryDirectory.

display.getCurrentStage() Returns the current stage object.

display.setStatusBar( mode ) Hides or changes the appearance of the status bar. The argument mode should be one of:

• display.HiddenStatusBar

• display.DefaultStatusBar

• display.TranslucentStatusBar

• display.DarkStatusBar

transition

The transition library allows you to animate a display object by tweening one or more properties of an object (e.g. a display object) over a speci"ed duration.

transition.to( target, params )Returns a tween that animates properties in the display object target over time. The "nal property values are speci"ed in the params table. To customize the tween, you can optionally specify the following non-animating properties in params:

• params.time speci"es the duration of the transition in milliseconds. By default, the duration is 500 ms (0.5 seconds).

• params.transition is by default easing.linear . See easing for more functions.

• params.delay speci"es the delay (none by default) before the tween begins.

• params.delta is a boolean specifying whether non-control parameters are interpreted as "nal ending values or as changes in value. The default is nil meaning false.

• params.onStart is a function or table listener called before the tween begins. Table listeners must have an onStart method. When invoked, the listener is given target instead of an event.

February 3, 2010 | © 2009 Ansca Inc. All Rights Reserved. 37

• params.onComplete is a function or table listener called after the tween completes.

The transition library eliminates the need for manually animating objects. Compare the following code that causes a white rectangle to fade out in 1 second:

Manual animation Using transition

local rect = display.newRect( 0, 0, 100, 100 )rect:setFillColor(255,255,255)

local tMax =1000+system.getTimer()local function fadeOut(event) local t = event.time local rect = event.target if t < tMax then rect.alpha = 1 - t/tMax else rect.alpha = 0 -- done, so remove listener Runtime:removeEventListener( "enterFrame", fadeOut ) endend

-- Add listener to begin animationRuntime:addEventListener( "enterFrame", fadeOut )

local rect = display.newRect( 0, 0, 100, 100 )rect:setFillColor(255,255,255)

transition.to( rect, {time=1000, alpha=0})

transition.cancel( tween )Cancels the tween.

transition.dissolve( src, dst, duration, delayDuration )

easing

The easing library is a collection of interpolation functions used by the transition library:

easing.linear( t, tMax, start, delta )

easing.inQuad( t, tMax, start, delta )

easing.outQuad( t, tMax, start, delta )

easing.inOutQuad( t, tMax, start, delta )

easing.inExpo( t, tMax, start, delta )

easing.outExpo( t, tMax, start, delta )

easing.inOutExpo( t, tMax, start, delta )

February 3, 2010 | © 2009 Ansca Inc. All Rights Reserved. 38

You can create your own easing function to interpolate between a start and a "nal value. The arguments of the function are de"ned as:

t is the time since the transition started

tMax is the duration of the transition

start is the starting value

delta is the change in value ("nal value = start + delta)

timer

Sometimes, it is useful to be able to call a function some time in the future rather than immediately. The timer library provides some basic functions to let you accomplish this.

timer.performWithDelay( delay, listener [, iterations] ) Invokes listener after delay milliseconds; returns a handle you can pass to timer.cancel() to cancel the timer before it invokes listener.

The listener can be either a function listener or a table listener. If listener is a table, it must have a timer method because timer events are sent to the listener. An optional parameter iterations speci"es the number of times listener is invoked. By default, it is 1; pass 0 if you want it to loop forever.

Function Listener Table Listener

local function listener( event ) print( "listener called" )end

timer.performWithDelay( 1000, listener )

local listener = {}function listener:timer( event ) print( "listener called )end

timer.performWithDelay( 1000, listener )

timer.cancel( timerId ) Cancels the timer operation associated with timerId.

local t = {}function t:timer( event ) local count = event.count print( "Table listener called " .. count .. " time(s)" ) if count >= 3 then timer.cancel( self.source ) -- after 3rd invocation, cancel timer endend

-- Register to call t's timer method an infinite number of timestimer.performWithDelay( 1000, t, 0 )

February 3, 2010 | © 2009 Ansca Inc. All Rights Reserved. 39

media

The media library provides access to the multimedia features of the device.

Audio

media.newEventSound( soundFile )Loads the event sound (1-3 seconds) from soundFile and returns an event sound id that can be passed to media.playEventSound. Currently, the sound "le must be in the application resources directory (see system.ResourceDirectory).

media.playEventSound( sound )Plays an event sound (1-3 seconds). The argument sound can be either an event sound id or a "lename for the event sound. Recommended for short sounds, especially to avoid animation “hiccups.” Returns the same thing as media.newEventSound.

local soundID = media.newEventSound( "beep.caf" )local playBeep = function() media.playEventSound( soundID )endtimer.performWithDelay( 7500, playBeep, 0 )

The following functions should be used to play longer duration sound. You can only have one sound "le open at a time.

media.playSound( soundFile )

media.pauseSound()

media.stopSound()

Supported Audio Formats

For the iPhone:

• Event sound "les should be:

• Short (several seconds)

• In linear PCM or IMA4 (IMA/ADPCM) format

• Packaged in a .caf or .aif "le.

• For the highest quality event sounds, use 16-bit, little endian, linear PCM audio data packaged in the Core Audio Format (.caf). On Mac OS X use the afconvert command:

/usr/bin/afconvert -f caff -d LEI16 {INPUT} {OUTPUT}

• For more compact event sound "les, use IMA4 format:

February 3, 2010 | © 2009 Ansca Inc. All Rights Reserved. 40

/usr/bin/afconvert -f caff -d ima4 {INPUT} {OUTPUT}

• For longer sounds, use media.playSound() to play .mp3 "les.

Video

media.playVideo( path [, baseSource ], showControls, listener )Plays the path in a device-speci"c popup media player. The optional parameter baseSource controls how path is interpreted and can be one of the system-de"ned directory constants or media.RemoteSource. In the former, the path is treated relative to the source base directory; in the latter, the path is treated as an absolute URL to a remote "le. By default it is system.ResourceDirectory.

During video playback, the media player interface takes over. If showControls is false, then the user can adjust playback, e.g. start, stop, seek, etc. Pass a listener to get noti"ed when the video has ended. Note this function is asynchronous. Any code that follows will be executed. After that, the application will be suspended until the video playback is complete.

local onComplete = function(event) print( "video session ended" )endmedia.playVideo( "Movie.m4v", true, onComplete )

The listener can be either a function listener or a table listener. If listener is a table, it must have a completion method. The event dispatched to the listener will be a completion event.

Supported Video Formats

For the iPhone:

• The video player supports playback of movie "les with the .mov, .mp4, .m4v, and .3gp "lename extensions and using the following compression standards:

• H.264 Baseline Pro"le Level 3.0 video, up to 640 x 480 at 30 fps. Note: B frames are not supported in the Baseline pro"le.

• MPEG-4 Part 2 video (Simple Pro"le)

Camera and Photo Library

media.show( imageSource, listener )Opens a platform-speci"c interface. This function returns immediately so the calling code will continue to execute until the end of its scope. By default, it is added at the top of the current stage. A listener is required. imageSource can be one of:

• media.PhotoLibrary

February 3, 2010 | © 2009 Ansca Inc. All Rights Reserved. 41

• media.Camera

• media.SavedPhotosAlbum

Note this function is asynchronous. Any code that follows will be executed. After that, the application will be suspended until the session is complete.

local onComplete = function(event) local photo = event.target print( "photo w,h = " .. photo.width .. "," .. photo.height )endmedia.show( media.Camera, onComplete )

The listener can be either a function listener or a table listener. If listener is a table, it must have a completion method. The event dispatched to the listener will be a completion event with the following additional properties:

event.target is a display image object based on the imageSource parameter.

native

The native library provides access to various native UI features on the device.

Activity Indicator

native.setActivityIndicator( visible )Displays or hides a platform-speci"c activity indicator. Touch events are ignored while the indicator is shown.

Note: the indicator will not show until the end of the Lua code block has completed execution.

Below are examples of how the activity indicator varies across platforms using the same code. Pictured on the left is the Corona Simulator on Mac OS X. Pictured on the right is the same app running on the iPhone.

February 3, 2010 | © 2009 Ansca Inc. All Rights Reserved. 42

Alert

native.showAlert( title, message [, buttonLabels [, listener]] )Displays a popup alert box with one or more buttons, using a native alert control. Program activity, including animation, will continue in the background, but all other user interactivity will be blocked until the user selects a button or cancels the dialog.

The strings title and message are the title and message text displayed in the alert. buttonLabels is a table of strings, each of which will create a button with the corresponding label. You should include at least one buttonLabel, or the dialog will not have any buttons. The "rst button will have a unique color to suggest that the user should choose it by default.

The maximum number of buttons in an alert box is six. The most common format is one or two buttons, for example “OK” and “Cancel”.

The listener is noti"ed when a user presses any button in the alert box, and it can assign an action to each button according to its numerical index: the "rst button is index 1, the second is index 2, and so on. The listener can be either a function listener or a table listener. If listener is a table, it must have a completion method. The event dispatched to the listener will be a completion event. It will contain the following additional properties:

event.action indicates how the alert was dismissed:

• "cancelled" indicates that native.cancelAlert() was called to close the alert.

• "clicked" indicates that the user clicked on a button to close the alert.

event.index is the index of the button pressed. It corresponds to the index in the buttonLabels parameter.

February 3, 2010 | © 2009 Ansca Inc. All Rights Reserved. 43

-- Handler that gets notified when the alert closeslocal function onComplete( event ) if "clicked" == event.action then local i = event.index if 1 == i then -- Do nothing; dialog will simply dismiss elseif 2 == i then -- Open URL if "Learn More" (the 2nd button) was clicked system.openURL( "http://developer.anscamobile.com" ) end endend

-- Show alert with five buttonslocal alert = native.showAlert( "Corona", "Dream. Build. Ship.", { "OK", "Learn More" }, onComplete )

Note: When running in the Corona Simulator, the alert box displayed will be a native Mac OS X alert sheet rather than an iPhone alert box (shown at left). On the iPhone, the alerts will function the same as native alerts (right):

native.cancelAlert( alert )Dismisses the alert box programmatically. For example, you may wish to have a popup alert that automatically disappears after ten seconds even if the user doesn’t click it. In that case, you could call this function at the end of a ten-second timer.

February 3, 2010 | © 2009 Ansca Inc. All Rights Reserved. 44

-- Dismisses “alert” from previous code sample after 10 secondslocal function cancelMyAlert() native.cancelAlert( alert )end

timer.performWithDelay( 10000, cancelMyAlert )

ExamplesFor further examples of how to use native alerts, see the Alert project in the Sample Code folder of the Corona SDK.

Fonts

native.newFont( name [, size] )Creates a font object that you can use to specify fonts in native text "elds and text boxes. You can also pass it as a parameter to the display text objects in the display.newText() function.

The name parameter is a string that names the font. You can obtain an array of available fonts via native.getFontNames(). Alternatively, you can also pass the following constants instead of a string:

• native.systemFont

• native.systemFontBold

The size parameter is optional. You can use it to specify the point size of the font. By default, it will be the standard system font size of the device.

native.getFontNames()Returns an array of the available native fonts. Pass

Note: On the simulator, the available fonts may not correspond to the actual available fonts on the device.

Text Input

native.newTextField( left, top, width, height [, listener] )Creates a single-line text"eld for text input.

Properties:

• object.align can be a string "left", "center", or "right".

• object.font is a font object returned by native.newFont().

• object.isSecure is controls whether text is hidden, e.g. passwords, or not. Default is false.

• object.size is the size of the text

• object.text is a string of the contents of the text box.

February 3, 2010 | © 2009 Ansca Inc. All Rights Reserved. 45

Methods:

• object:setTextColor( r, g, b [, a] )

Note: Only available on device builds.

native.setKeyboardFocus( textField )Sets keyboard focus on a textField and (where appropriate) shows the keyboard. Pass nil to remove focus and dismiss the keyboard.

Note: Only available on device builds.

Native text"elds do not obey the display object hierarchy. For example, they always appear above normal display objects.

Text Scrolling

native.newTextBox( left, top, width, height )Creates a scrollable, multi-line text box

Properties:

• object.align can be a string "left", "center", or "right".

• object.font is a font object returned by native.newFont().

• object.hasBackground is true when there is background and false when the background is transparent.

• object.size is the size of the text

• object.text is a string of the contents of the text box.

Methods:

• object:setTextColor( r, g, b [, a] )

Note: Only available on device builds.

Native textboxes do not obey the display object hierarchy. For example, they always appear above normal display objects.

Web Popup

native.showWebPopup( url [, options] )Creates a fullscreen web popup that loads a local or remote web page speci"ed by url. By default, the url is assumed to be an absolute url to a remote server.

The options parameter is optional. You can customize certain features by creating a table with the following properties:

• object.baseUrl determines whether url is interpreted as a relative or absolute url. The default (nil) implies that the url is absolute. To load a local "le, set the base url to one of the base directory constants, e.g. system.ResourceDirectory. Then the url

February 3, 2010 | © 2009 Ansca Inc. All Rights Reserved. 46

parameter is relative to that base directory. For remote "les, you can also specify a remote base, and the url parameter will be relative to the remote base.

• object.hasBackground controls whether the popup has a an opaque background or not. It not speci"ed, the background will be opaque.

• object.urlRequest is a function or table listener to urlRequest events.

Note: Only available on device builds.

native.cancelWebPopup()Dismisses the web popup. Returns true if web popup was displaying prior to the call; false otherwise.

Note: Only available on device builds.

system

system.getPreference( category, name )Returns a preference value as a string. Valid values of category are:

• "ui" for general application-level preferences. In this category, pass "language" for the name parameter to get the preferred language.

• "locale" for locale preferences. In this category, valid name parameters include "country", "identi!er", and "language".

system.getTimer() Returns time in milliseconds since application launch.

system.openURL( url )Opens url. NOTE: we may change this slightly.

Supported url formats for the iPhone:

• Mail links: mailto:[email protected].

• Phone links: tel:415-867-5309.

• Web links: http://www.anscamobile.com.

system.pathForFile( !lename [, baseDirectory] )Generates an absolute path using system-de"ned directories as the base (see “System-de"ned directories” below). A second, optional parameter baseDirectory speci"es which base directory is used to construct the full path; its default values is system.ResourceDirectory. If the base directory is system.ResourceDirectory and the generated path points to a non-existent "le, nil is returned.

system.setAccelerometerInterval( frequency )Sets the frequency of accelerometer events. The min frequency is 10 Hz and the max is 100 Hz on the iPhone. Accelerometer events are a signi"cant drain on battery, so only increase the frequency when you need faster responses as in games. Always try to lower the frequency whenever possible to conserve battery life.

February 3, 2010 | © 2009 Ansca Inc. All Rights Reserved. 47

system.setIdleTimer( enabled )Controls whether the idle timer is enabled. If enabled is true, the timer will be active (default); inactive if false. When active, the idle timer dims the screen and eventually puts the device to sleep when no user activity occurs (e.g. screen touches).

system.setLocationAccuracy( distance )Sets the desired accuracy of location events to distance meters. Note: the actual accuracy depends on the capabilities of the device and/or platform. On the iPhone, accuracy is limited to discrete distances: <10, 10, 100, 1000, and 3000. Higher accuracy (smaller distances) requires more battery life, so use larger distance to preserve battery life.

system.setLocationThreshold( distance )Sets how much distance in meters must be travelled until the next location event is sent. Because location events involve hardware that can drain the battery, using larger threshold distances preserve battery life.

system.vibrate()Vibrates the phone.

System-de!ned directories

The following are constants for base directories to be used with system.pathForFile().

system.DocumentsDirectory should be used for "les that need to persist between application sessions. Under the simulator, the user's documents directory is used, e.g. "~/Documents"

system.TemporaryDirectory is a temporary directory. Files written to this directory are not guaranteed to exist in subsequent application sessions. They might exist or they might not.

system.ResourceDirectory is the directory where all application assets exist. On the simulator, this corresponds to "les located in the assets folder of your project. For example, this is the default location where display.newImage() looks for image "les. Note: you should never create, modify, or add "les to this directory. Doing so will prevent the device from verifying the integrity of your application; in some cases, the device will treat your application as malware and refuse to launch your application.

contacts

Forthcoming

February 3, 2010 | © 2009 Ansca Inc. All Rights Reserved. 48

Display Objects

All drawing that occurs on the screen is accomplished by creating DisplayObjects. Anything that appears on the screen is an instance of a DisplayObject. You don't actually create these objects directly. Instead, you create special kinds of DisplayObjects such as rectangles, circles, images, text, etc.

These objects are all "rst-class citizens. You can animate them, turn them into buttons, etc.

You create a DisplayObject by calling a special kind of function called a constructor. This implicitly adds the object above all other objects you have created. DisplayObjects are designed to organize common functionality, but you never create a DisplayObject explicitly.

Instead, there are constructors for each speci"c kind of DisplayObject, e.g. display.newRect() creates a VectorObject.

All display object constructors implicitly set the parent of the new objects to be the current stage object.

All instances of DisplayObject behave like normal Lua tables. This means you can add your own properties to the object as long as they don't con$ict with the properties and method names below. Group objects (and stage objects) have some slight quirks as discussed below.

In addition, all display objects have the following properties and object methods in common:

Common Properties

Properties are accessed via the dot operator. For example, if we have a DisplayObject represented by the variable object, we can change its alpha to 50%: object.alpha=0.5.

Below are the common properties shared by all display objects.

object.alpha is the opacity. A value of 0 is transparent and 1.0 is opaque.

object.height is in local coordinates

object.isVisible controls whether the object is visible on the screen.

object.isHitTestable allows an object to continue to receive hit events even if it is not visible. If false, objects will receive hit events regardless of visibility; if false, events are only sent to visible objects.

object.length [read-only] is deprecated in favor of group.numChildren. For Group Objects, this is the number of children; 0 otherwise.

object.parent [read-only]

February 3, 2010 | © 2009 Ansca Inc. All Rights Reserved. 49

object.rotation is in local coordinates

object.stageBounds is a table with properties xMin, xMax, yMin, yMax in screen coordinates.

object.stageHeight is the height in screen coordinates.

object.stageWidth is the width in screen coordinates.

object.width is in local coordinates

object.x speci"es the x-position (in local coordinates) of the object relative to the parent — the parent's origin to be precise. Speci"cally, it provides the x-position of the object’s reference point relative to the parent. Changing the value of this will move the object in the x-direction.

object.xOrigin speci"es the x-position of the object's origin relative to the parent's origin. It is in the object's local coordinates. Changing the value of this will move the object in the x-direction.

object.xReference de"nes the x-position of the reference point relative to the object's local origin. It is relative to another point in the object, not to its parent. Conceptually, the reference point is the location about which scaling and rotations occur. Sometimes this is referred to as the registration point. For most display objects, this value defaults to 0, meaning the x-position of the origin and the reference point are the same. This merely de"nes the reference point, so changing the value of this property does not change the position of the object.

object.xScale affects the local transform

object.y speci"es the y-position (in local coordinates) of the object relative to the parent — the parent's origin to be precise. Speci"cally, it provides the x-position of the object’s reference point relative to the parent. Changing the value of this will move the object in the y-direction.

object.yOrigin speci"es the y-position of the object's origin relative to the parent's origin. It is in the object's local coordinates. Changing the value of this will move the object in the y-direction.

object.yReference de"nes the y-position of the reference point relative to the object's local origin. It is relative to another point in the object, not to its parent. Conceptually, the reference point is the location about which scaling and rotations occur. Sometimes this is referred to as the registration point. For most display objects, this value defaults to 0, meaning the y-position of the origin and the reference point are the same. This merely de"nes the reference point, so changing the value of this property does not change the position of the object.

object.yScale affects the local transform

Common Object Methods

Object methods are accessed via the colon operator. For example, if we have a DisplayObject represented by the variable object, we can translate the object 10 pixels to the right: object:translate( 10, 0 ).

Below are the common methods shared by all display objects:

February 3, 2010 | © 2009 Ansca Inc. All Rights Reserved. 50

object:getParent() is deprecated in favor or object.parent. (Yes, you should ignore the fact that sample code continues to use this API).

object:rotate( deltaAngle ) effectively adds deltaAngle to the rotation property.

object:scale( sx, sy ) effectively multiplies xScale and yScale properties by sx and sy respectively.

object:setReferencePoint( referencePoint ) sets the reference point either to the center of the object (default) or to one of several convenient points along the bounding box of the object. The argument referencePoint should be one of:

• display.CenterReferencePoint

• display.TopLeftReferencePoint

• display.TopCenterReferencePoint

• display.TopRightReferencePoint

• display.CenterRightReferencePoint

• display.BottomRightReferencePoint

• display.BottomCenterReferencePoint

• display.BottomLeftReferencePoint

• display.CenterLeftReferencePoint

object:translate( deltaX, deltaY ) effectively adds deltaX and deltaY to the x and y properties respectively.

Vector Objects

Vector objects are a special type of DisplayObject. In addition to the properties and methods of Display Object

Constructor

The following return Lua tables representing rectangle, rounded rectangle, and circle, respectively:

display.newRect( left, top, width, height ) creates a width by height rectangle with the top-left corner at (left, top). The local origin is at the center of the rectangle; the reference point is initialized to this local origin. By default, there is no "ll or stroke color.

display.newRoundedRect( left, top, width, height, cornerRadius ) creates a width by height rounded rectangle with the top-left corner at (left, top). The corners are rounded by quarter circles of radius cornerRadius. The local origin is at the center of the rectangle; the reference point is initialized to this local origin. By default, there is no "ll or stroke color.

February 3, 2010 | © 2009 Ansca Inc. All Rights Reserved. 51

display.newCircle( xCenter, yCenter, radius ) creates a circle with radius radius centered at (xCenter, yCenter). The local origin is at the center of the circle; the reference point is initialized to this local origin. By default, there is no "ll or stroke color.

Properties

object.strokeWidth

Object Methods

Vector objects have the following additional methods:

object:setFillColor( r, g, b [, a] ) All components must be between 0 and 255. Alpha is optional and is 255 (opaque) by default.

object:setStrokeColor( r, g, b [, a] ) All components must be between 0 and 255. Alpha is optional and is 255 (opaque) by default.

Images

Image objects are a type of DisplayObject.

Constructor

display.newImage( !lename [, baseDirectory] [, left, top] ) returns an image object. It loads the image data from filename and by default looks in the system.ResourceDirectory for that "le. If you specify the argument baseDirectory it will look in that directory instead (see system.pathForFile for valid values of baseDirectory).

You can specify that the image's top-left corner be located at the coordinate (left, top); if you don't supply both coordinates, the image will be centered about its local origin.

The local origin is at the center of the image; the reference point is initialized to this local origin.

Text

Constructor

display.newText( string, x, y, nil, size ) creates a text object with its top-left corner at (x, y). The fourth argument is nil and is reserved for future use. The local origin is at the center of the text; the reference point is initialized to this local origin. By default, there is no text color.

Properties

object.text is a string that contains the text of the text"eld

February 3, 2010 | © 2009 Ansca Inc. All Rights Reserved. 52

object.size is the size of the text

Object Methods

Text objects have the following additional methods:

object:setTextColor( r, g, b [, a] ) All components must be between 0 and 255. Alpha is optional and is 255 (opaque) by default.

Groups

Group objects are a special type of DisplayObject. You can add other display objects as children of a group object. You can also remove them. Even if an object is not visible, it remains in the group object until explicitly removed. Thus, to minimize memory consumption, you should explicitly remove any object that will no longer be used.

All objects are implicitly added to the current stage which itself is a kind of group object.

The children of group objects are simply other display objects (vector, groups, etc.). They are accessed by integer index. The "rst child is at index 1. Note that the Lua table library functions such as (table.insert) are incompatible with groups.

Constructor

display.newGroup() creates a group in which you can add and remove child display objects. Initially, there are no children in a group. The local origin is at the parent's origin; the reference point is initialized to this local origin.

Properties

group.numChildren returns the number of children. You access the children by integer index:

local group = display.newGroup()group:insert( rect1 ) -- assume rect1 is an existing display objectgroup:insert( rect2 ) -- assume rect2 is an existing display object

for i=1,group.numChildren do local child = group[i] local description = (child.isVisible and "visible") or "not visible" print( "child["..i.."] is " .. description )end

Object Methods

Group objects have the following additional methods:

February 3, 2010 | © 2009 Ansca Inc. All Rights Reserved. 53

group:insert( [index,] child, [, resetTransform] ) Inserts child at index into group, shifting up other elements as necessary. The default value index is n+1 where n is the number of children in the group. The resetTransform parameter determines what happens to child's transform. When false, child's local position, rotation, and scale properties are preserved, except the local origin is now relative to the new parent group, not its former parent; when false, child's transform is reset (i.e. the x, y, rotation, xScale, and yScale properties of child are reset to 0, 0, 0, 1, and 1, respectively). The default value for resetTransform is false. An easy way to move an object above its siblings is to re-insert it: object.parent:insert( object ).

group:remove( indexOrChild ) Removes from group the display object speci"ed by indexOrChild, shifting down other elements as needed. The argument indexOrChild is either the index position of the child within group or the child display object itself. In either case, it returns the removed display object.

Stage

Stage objects are a special type of GroupObject, so all methods and properties of group objects are available in stage objects. You access the current stage object using display.getCurrentStage().

All objects are implicitly added to the current stage which itself is a kind of group object.

Object Methods

stage:setFocus( displayObject ) sets displayObject as the target for all future hit events. Pass nil, to restore default behavior for hit event dispatches. This is typically used to implement buttons that change appearance when a user initially presses it.

February 3, 2010 | © 2009 Ansca Inc. All Rights Reserved. 54

Events and Listeners

Events are dispatched to listeners. Event listeners can be either functions or objects (see Listeners below). In both cases, when an event occurs, the listener will be invoked and be supplied with a table representing the event. All events will have a property name that identi"es the kind of event.

Registering for Events

Certain objects you create using Ansca's libraries are event listeners. This includes both display objects and the global Runtime object. You can add and remove listeners for events using the following object methods:

object:addEventListener( eventName, listener )Adds listener to the object’s list of listeners. When an event corresponding to the string eventName occurs is dispatched, the listener will be noti"ed of the event. Listeners can be either a function or a table with a method called eventName.

object:removeEventListener( eventName, listener )Removes listener from the global list so that it no longer is noti"ed of global events corresponding to the string eventName.

Examples

In the example below, an image display object registers to receive touch events. Touch events are not broadcast globally. Only objects that register for the event and lie underneath it will be candidates for receiving the touch. See Touch Events for more information.

Function Listeners Table Listeners

local button = display.newImage("button.png")

local listener = function(event) print(event.name.."occurred") return trueend

button:addEventListener( "touch", listener )

local button = display.newImage("button.png")

function button:touch(event) print(event.name.."occurred") return trueend

button:addEventListener( "touch", listener )

February 3, 2010 | © 2009 Ansca Inc. All Rights Reserved. 55

In contrast, Runtime events are dispatched by the system. They are broadcast to all listeners. Below is an example of registering for an enterFrame event:

Function Listeners Table Listeners

local listener = function(event) print(event.name.."occurred")end

Runtime:addEventListener( "enterFrame", listener )

local listener = {}function listener:touch(event) print(event.name.."occurred")end

Runtime:addEventListener( "enterFrame", listener )

Function vs Table Listeners

Listeners can be either functions or table objects.

When a function listener is invoked, it is passed a table representing the event:

local myListener = function( event ) print( "Listener called with event of type " .. event.name )endRuntime:addEventListener( "touch", myListener )Runtime:addEventListener( "enterFrame", myListener )

Sometimes a function listener is not convenient because certain variables are not in scope when the listener is triggered (invoked). In these situations, object listeners should be used. Object listeners must have an instance method with a name corresponding to the event name:

-- assume MyClass and MyClass:new() already exist

function MyClass:enterFrame( event ) print( "enterFrame called at time: " .. event.time )end

function MyClass:touch( event ) print( "touch occurred at ("..event.x..","..event.y..")" )end

local myObject = MyClass:new()

Runtime:addEventListener( "touch", myObject )Runtime:addEventListener( "enterFrame", myObject )

February 3, 2010 | © 2009 Ansca Inc. All Rights Reserved. 56

Runtime Events

Runtime events are only sent to the global Runtime object because there is no speci"c target. Instead, they are broadcast to all registered listeners. The events all have string names:

enterFrame

Frame events occur at the frame interval of the application. They are only sent to the global Runtime object.

The following properties are available in this event:

event.name is the string "enterFrame".

event.time is the time in milliseconds since the start of the application.

system

System events are dispatched to notify the application of external events such as when the device needs to suspend the application because of an incoming phone call. These events are only sent to the global Runtime object.

The following properties are available in this event:

event.name is the string "system".

event.type is a string identifying the type of event. The string values could be:

• "applicationStart" occurs when the application is launched and all code in main.lua is executed.

• "applicationExit" occurs when the user quits the application.

• "applicationSuspend" occurs when the device needs to suspend the application such as during a phone call or if the phone goes to sleep from inactivity. In the simulator, this corresponds to the simulator running in the background. During suspension, no events (not even enterFrame events) are sent to the application while suspended, so if you have code that depends on time, you should account for the time lost to an application being suspended.

• "applicationResume" occurs when the application resumes after a suspend. On the phone, this occurs if the application was suspended because of a phone call. On the simulator, this occurs when the simulator was in the background and now is the foreground application.

orientation

Orientation events occur when the device orientation changes. They only occur on devices with accelerometer support. They are only sent to the global Runtime object.

The following properties are available in this event:

February 3, 2010 | © 2009 Ansca Inc. All Rights Reserved. 57

event.name is the string "orientation".

event.type is a string identifying the orientation:

• "portrait"

• "landscapeLeft"

• "portraitUpsideDown"

• "landscapeRight"

• "faceUp"

• "faceDown"

event.delta is the angular difference between the ending and starting orientation. 0 if the two orientations lie in different planes.

accelerometer

NOTE: This is experimental. This event is the dumping ground for all accelerometer properties. We may break this into separate events.

Accelerometer events let you detect sudden movements and determine the device's orientation relative to gravity. These events are only dispatched on devices that have support accelerometer. They are only sent to the global Runtime object.

The following properties are available in this event:

event.name is the string "accelerometer".

event.xGravity is the acceleration due to gravity in the x-direction

event.yGravity is

event.zGravity is

event.xInstant is the instantaneous acceleration in the x-direction

event.yInstant is

event.zInstant is

event.isShake is false when the user shakes the device.

location (GPS)

Location events. Note: this event is not available on all devices. They are only sent to the global Runtime object.

If no errors occurred, the following properties are available in this event:

event.name is the string "location".

event.latitude is the latitude in degrees.

February 3, 2010 | © 2009 Ansca Inc. All Rights Reserved. 58

event.longitude is the longitude in degrees.

event.altitude is the altitude in meters.

event.accuracy is the accuracy of the location in meters. If negative, then the latitude and longitude are not valid.

event.speed is the instantaneous speed of the device in meters per second.

event.direction is the direction the device is travelling in degrees clockwise from true North. If negative, the direction is invalid.

event.time is the UTC timestamp of the location event.

When an error occurs, the following properties will be non-nil:

event.errorMessage is a string with an error description. This property only exists when an error occurs. It may be localized so it may vary depending on the user’s language setting.

event.errorCode is a platform-speci"c integer for the error which is not language dependent. This property only exists when an error occurs.

heading (compass)

Heading events. Note: this event is not available on all devices. They are only sent to the global Runtime object.

The following properties are available in this event:

event.name is the string "heading".

event.geographic represents a heading in degrees (clockwise) relative to the geographic North Pole, sometimes known as true North.

event.magnetic represents a heading in degrees (clockwise) relative to the magnetic North Pole.

Targeted Events

Targeted events are not broadcast. They are sent to a single target (a function or table listener).

completion

Completion events signal the end of an interaction. Typically these are dispatched at the end of a modal interaction such as using the camera or throwing up a native alert.

The following are common properties of this event:

event.name is the string "completion".

Additional properties are given depending on the modal interaction (see media.playVideo, media.show, and native.showAlert).

February 3, 2010 | © 2009 Ansca Inc. All Rights Reserved. 59

timer

Timer events are used in conjunction with the timer library.

The following properties are available in this event:

event.name is the string "timer".

event.source corresponds to the timer registered to send the event.

event.count is the number of times that the timer has "red the listener. This is useful if you registered the timer to "re multiple times.

event.time is the time in milliseconds since the start of the application.

urlRequest

URL request events are dispatched to the listener registered with the native.webPopup() function. They are sent when the web popup is about to request a url and also when a url fails to load.

The following properties are available in this event:

event.name is the string "urlRequest".

event.url is the absolute URL of the request.

event.errorMessage is a string with an error description. This property only exists when an error occurs. It may be localized so it may vary depending on the user’s language setting.

event.errorCode is a platform-speci"c integer for the error which is not language dependent. This property only exists when an error occurs.

Touch Events

When the user’s "nger touches the screen, a hit event is generated and dispatched to display objects in the display hierarchy. Only those objects that intersect the hit location (the location of the "nger on the screen) will be candidates for receiving the event.

The events propagate through these objects in a particular order. The "rst object in the display hierarchy to receive the event is the top-most display object that intersects the hit location; the next object is the next top-most object intersecting the hit location; and so on.

Hit events propagate until they are handled. You can stop propagation to the next object (all listeners of the current object still get the event) by telling the system that the event was handled. This boils down to making a listener return true. If at least one of the listeners of the current object returns true, event propagation ends; the next object will not get the event. If the event is still unhandled at the end of this traversal, it is broadcast as a global event to the global Runtime object.

Hit events are a hybrid of local and global events. They are dispatched to a single display object at a time, but any listener registered with that display object will receive the event.

February 3, 2010 | © 2009 Ansca Inc. All Rights Reserved. 60

In some situations, it is convenient to have subsequent events target the same object that handled the initial touch event (a user’s "nger initially touching the screen). To accomplish this, you can use a special method display.getCurrentStage():setFocus( object ). When the user’s "nger is lifted, you can call the method again and pass nil to restore the default behavior.

touch

Touch events are a special kind of hit event. When a user’s "nger touches the screen, they are starting a sequence of touch events, each with different phases.

event.name is the string "touch".

event.x is the x-position in screen coordinates of the touch.

event.y is the y-position in screen coordinates of the touch.

event.xStart is the x-position of the touch from the "began" phase of the touch sequence.

event.yStart is the y-position of the touch from the "began" phase of the touch sequence.

event.phase is a string identifying where in the touch sequence the event occurred:

• "began" a "nger touched the screen.

• "moved" a "nger moved on the screen.

• "stationary" a "nger is touching the screen but hasn’t moved from the previous event.

• "ended" a "nger was lifted from the screen.

• "cancelled" the system cancelled tracking of the touch.

multitouch

Forthcoming.

tap

NOTE: Experimental. May not be available in future versions.

The following properties are available in this event:

event.name is the string "tap".

event.x is the .

event.y is the .

event.numTaps .

drag

TODO: The name is misleading --- change to "$ick" or something similar. This was designed to simplify detection of horizontal and vertical movements.

February 3, 2010 | © 2009 Ansca Inc. All Rights Reserved. 61

NOTE: Experimental. May not be available in future versions.

The following properties are available in this event:

event.name is the string "drag".

event.x is the .

event.y is the .

event.xDelta .

event.yDelta .

Custom Events

In Corona, you can register custom events with both display objects and the global Runtime object. In both cases, you will have to manually dispatch the event yourself using the following object method:

object:dispatchEvent( event )Dispatches event to object. The event parameter must be a table with a name property which is a string identifying the type of event. The object parameter must be either a display object or the global Runtime object. If object has a listener registered to receive name events. We recommend you also include a target property to the event so that your listener can know which object received the event.

-- Create an object that listens to eventslocal image = display.newImage( "image.png" )

-- Setup listenerlocal myListener = function( event ) print( "Event " .. event.name ) print( "Target has width: " .. event.target.stageWidth )end

image:addEventListener( "myEventType", myListener )

-- Sometime later, create an event and dispatch itlocal event = { name="myEventType", target=image }image:dispatchEvent( event )

February 3, 2010 | © 2009 Ansca Inc. All Rights Reserved. 62

Corona Internal Libraries

Corona also has some additional built-in libraries. To speed up launch time, these are not automatically loaded by default. Hence to make these libraries available, you must explicitly load them using require.

• crypto provides routines for calculating common message digests (hashes) and hash-based message authentication codes (HMAC).

• socket provides networking access.

crypto

Corona includes functions for calculating hash and HMAC (hash-based message authentication codes). Although these libraries are built into Corona, you need to use the Lua require syntax to make the functions available to your code, e.g. placing local crypto = require("crypto") at the top of your Lua "le.

crypto.digest( algorithm, string [, raw] )This function generates the message digest of the input string and returns it. See Algorithm Constants for valid values for algorithm. The optional raw $ag, defaulted to false, is a boolean indicating whether the output should be a direct binary equivalent of the message digest, or formatted as a hexadecimal string (the default).

crypto.hmac( algorithm, string, key [, raw] )This function returns HMAC of the string and returns it. See Algorithm Constants for valid values for algorithm. The parameter key is used as the seed for the HMAC generation. The optional raw $ag, defaulted to false, is a boolean indicating whether the output should be a direct binary equivalent of the HMAC or formatted as a hexadecimal string (the default).

Algorithm Constants

The algorithm parameter is a constant for a hashing algorithm:

• crypto.md4 (Note: HMAC is not available for this algorithm)

• crypto.md5

• crypto.sha1

• crypto.sha224

• crypto.sha256

• crypto.sha384

• crypto.sha512

February 3, 2010 | © 2009 Ansca Inc. All Rights Reserved. 63

socket (Networking)

Corona includes the latest version (v2.02) of the LuaSocket libraries. These Lua modules implement common network protocols such as SMTP (sending e-mails), HTTP (WWW access) and FTP (uploading and downloading "les). Also included are features to support MIME (common encodings), URL manipulation and LTN12 (transferring and "ltering data).

Full LuaSocket documentation can be found here:

http://www.tecgraf.puc-rio.br/~diego/professional/luasocket/reference.html

Although these libraries are built into Corona, you need to use the Lua require syntax to make the functions available to your code. This is demonstrated in the example below, and in other online code samples available from the global Lua community.

Simple image downloading

This example uses the http.request function to download a PNG "le, save it to a local directory, and then display it as an image. JPEG "les can also be downloaded and displayed in this manner.

-- Load the relevant LuaSocket moduleslocal http = require("socket.http")local ltn12 = require("ltn12")

-- Create local file for saving datalocal path = system.pathForFile( "hello.png", system.DocumentsDirectory )myFile = io.open( path, "w+b" )

-- Request remote file and save data to local filehttp.request{ url = "http://developer.anscamobile.com/demo/hello.png", sink = ltn12.sink.file(myFile),}

-- Display local filetestImage = display.newImage("hello.png",system.DocumentsDirectory,60,50);

When testing this code in the Corona Simulator, the Documents directory on your Mac stands in for the application’s local directory on the iPhone. As a result, you will see the downloaded PNG "le being stored in your Documents directory.

Examples

For an example of how to use this library, see the SimpleImageDownload project in the Sample Code folder of the Corona SDK.

February 3, 2010 | © 2009 Ansca Inc. All Rights Reserved. 64

External Libraries

Ansca Corona provides the following libraries as external modules that you can include in your application:

• sprite enables you to create animated sprites (movieclips).

• ui simpli"es common user interface tasks.

sprite

The sprite library is an external module, sprite.lua, that can be included with your projects and loaded using the require command (see the Module section of this document for further details on require). The current version of this library supports an Anim class for creating animated sprites (sometimes known as movieclips), including forward and reverse animation and jumping to named frames.

Anim (“Movieclip”)

sprite.newAnim( frames )Creates an animated sprite using an array of image "lenames provided in the frames table:

myAnim = sprite.newAnim{ "img1.png", "img2.png", "img3.png", "img4.png" }

object:play()Starts the animated sprite playing in the forward direction. When the end of the image sequence is reached, it will cycle back to the "rst image and continue playing.

object:reverse()Starts the animated sprite playing in the reverse direction. When the beginning of the image sequence is reached, it will cycle back to the last image and continue playing backwards.

object:stop()Stops the animation of the sprite at its current frame.

object:stopAtFrame( frame )Jumps the animation to the speci"ed frame, given either as a frame number or by an optional frame label (see setLabels function below).

Note: to “go to and play” from a speci"ed frame, simply issue a stopAtFrame command followed by a play or reverse command. Both commands will execute before the display updates again, and so the transition will be immediate:

February 3, 2010 | © 2009 Ansca Inc. All Rights Reserved. 65

myAnim:stopAtFrame(4)myAnim:play()

myAnim:stopAtFrame("label")myAnim:reverse()

object:setLabels( labels )Adds optional labels to an Anim object previously created, using a table to assign label names to selected frame numbers:

myAnim:setLabels{ firstLabel=1, anotherLabel=3 }

Note that these examples use the “shorthand” notation for passing a table of values directly to a function, as discussed in the Button section above.

ExamplesFor an example of how to use this library, see the Movieclip project in the Sample Code folder of the Corona SDK.

ui

The ui library is an external module, ui.lua, that can be included with your projects and loaded using the require command (see the Module section of this document for further details on require). The current version of this library supports a Button class that you can easily add to your programs.

Button

ui.newButton( params )Displays a button with normal and rollover states given by two speci"ed image "les. The button’s “press” and “release” events can each be used to call a function.

These image and function parameters are speci"ed in a params table with the following format:

February 3, 2010 | © 2009 Ansca Inc. All Rights Reserved. 66

local params = { default="button.png", rollover="button_over.png", onPress=pressFunction, onRelease=releaseFunction}

myButton = ui.newButton( params )

As simpler shorthand for the above, the parameter table can be directly provided to the newButton function:

myButton = ui.newButton{ default="button.png", rollover="button_over.png", onPress=pressFunction, onRelease=releaseFunction}

Once created, the button’s display properties (x, y, alpha, group, etc.) can be set just like any other Corona display object.

myButton.x = 200myButton.y = 150

ExamplesFor an example of how to use this library, see the Button project in the Sample Code folder of the Corona SDK.

February 3, 2010 | © 2009 Ansca Inc. All Rights Reserved. 67

Revision History

This table describes the changes to Corona API Reference:

Date Notes

2009-06-08 Initial draft

2009-11-28 Revised for product release 1.0

February 3, 2010 | © 2009 Ansca Inc. All Rights Reserved. 68


Recommended