+ All Categories
Home > Documents > A Pi Reference

A Pi Reference

Date post: 03-Apr-2018
Category:
Upload: gaurav-gulati
View: 221 times
Download: 0 times
Share this document with a friend

of 68

Transcript
  • 7/28/2019 A Pi Reference

    1/68

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

    Corona SDK

    Language and API Reference

  • 7/28/2019 A Pi Reference

    2/68

    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 Anscas 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 modication, 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 specic legal rights, and you may also have

    other rights which vary from state to state.

    Portions of chapter "Lua" and "Standard Libraries" are

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

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

    notice and this permission notice shall be included in allcopies or substantial portions of the Software.

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

    http://www.lua.org/manual/5.1/manual.htmlhttp://www.lua.org/manual/5.1/manual.html
  • 7/28/2019 A Pi Reference

    3/68

    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

  • 7/28/2019 A Pi Reference

    4/68

    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

  • 7/28/2019 A Pi Reference

    5/68

    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 46Web Popup 46

    system 47

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

  • 7/28/2019 A Pi Reference

    6/68

    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

  • 7/28/2019 A Pi Reference

    7/68

    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

  • 7/28/2019 A Pi Reference

    8/68

    Introduction

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

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

    We provide you with a consistent platform to build graphically-rich applications. As adeveloper, you will program in Lua, a simple and intuitive scripting language, and leverageAnscas innovative and robust APIs.

    This document will discuss how to use Anscas APIs 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 iPhoneapplications using Corona.

    A highly recommended detailed and authoritative introduction to all aspects of Luaprogramming by Luas chief architect: Programming in Lua (2nd edition), by RobertoIerusalimschy

    For an official denition 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 anexcellent place to see some simple sample programs and to play with your own.

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

    http://www.lua.org/manual/5.1/http://www.lua.org/demo.htmlhttp://www.lua.org/demo.htmlhttp://www.lua.org/http://www.lua.org/http://www.lua.org/manual/5.1/http://www.lua.org/manual/5.1/http://www.lua.org/manual/5.1/http://www.lua.org/manual/5.1/
  • 7/28/2019 A Pi Reference

    9/68

    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 identiers) in Lua can be any string of letters, digits, and underscores, notbeginning with a digit. This coincides with the denition of names in most languages. (Thedenition of letter depends on the current locale: any character considered alphabetic by thecurrent locale can be used in an identier.) Identiers are used to name variables and tableelds.

    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, butAnd andAND are two different,valid names. As a convention, names starting with an underscore (such as _VERSION) arereserved for use by Corona.

    Comments begin anywhere with a double hyphen (--) except inside a string. They run until theend 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 constantcan be written with an optional decimal part and an optional decimal

    exponent. Lua also accepts integer hexadecimal constants, by prexing 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

  • 7/28/2019 A Pi Reference

    10/68

    Types and Values

    Lua is a dynamically typed language. Unlike other languages, you do not need to declare thetype 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 youll deal with are:

    nil. Nil is a type with a single value, nil. By default, global variables are nil which means thatthey 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 conditionalexpressions, e.g. if ( condition ), both false and nil evaluate as false; everything elseevaluates 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 arraywhich is just a fancy way of saying that the array can be indexed not just by numbers, butalso by any other value of the language except nil. Typically, you would use a string as anindex (see Properties).

    Conversions between string and number

    Lua provides automatic conversion between string and number values at run time. Anyarithmetic 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, thenumber is converted to a string, in a reasonable format. For complete control over hownumbers are converted to strings, use the format function from the string library (seestring.format).

    Objects

    Tables and functions are objects: variables do not actually contain these values, only referencesto them. Assignment, parameter passing, and function returns always manipulate referencesto 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 valuesof all types (except nil). Tables are the sole data structuring mechanism in Lua; they can beused to represent ordinary arrays, symbol tables, sets, records, graphs, trees, etc. To representrecords (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

  • 7/28/2019 A Pi Reference

    11/68

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

    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"] (line6).

    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 byassigning nil to it. At this point, the global variable behaves as if it were never initialized:

    s = nil

    print( s ) --> nil

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

  • 7/28/2019 A Pi Reference

    12/68

    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. Thescope of the local variable begins after the declaration and ends at the end of the block.

    a = 10

    local i = 1

    while i 1, 4, 9, 16, 25, ...i = i + 1

    end

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

    Table elds (properties)

    Tableelds are just the elements of the table themselves. You index into the array to assign thevalues to a eld. When the index is a string, the eld is known as a property (see alsoProperties):

    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 theoperands are numbers, or strings that can be converted to numbers (see Conversions betweenstring and number), then all operations have the usual meaning. Exponentiation works for any

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

  • 7/28/2019 A Pi Reference

    13/68

    exponent. For instance, x^(-0.5) computes the inverse of the square root of x. Modulo isdened as

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

    That is, it is the remainder of a division that rounds the quotient towards minus innity.

    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 isfalse. Otherwise, the values of the operands are compared. Numbers and strings are comparedin the usual way. Objects (tables and functions) are compared by reference: two objects areconsidered equal only if they are the same object. Every time you create a new object (a tableor 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 areand, or, and not. All logical operators consider both false andnil 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. Thedisjunction 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 arestrings or numbers, then they are converted to strings.

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

  • 7/28/2019 A Pi Reference

    14/68

    Length Operator

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

    The length of a table t is dened 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 agiven n, its length is exactly that n, the index of its last value. If the array has "holes" (that is, nilvalues between other non-nil values), then #t can be any of the indices that directly precedes anil 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. Theconcatenation ('..') and exponentiation ('^') operators are right associative. All other binaryoperators are left associative.

    Properties

    Many Corona APIs return objects. You are free to manipulate the documented properties ofthese objects just like you would on a table. You can even add your own properties provided

    you do not prex any of your custom properties with an underscore (_). Ansca reserves theright 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 thesame.

    Functions

    Because functions can be variables, a table can store them as properties. This creates allows forvery exible uses of a table. It can be used to logically group a family functions into a table, e.g.

    themath 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

  • 7/28/2019 A Pi Reference

    15/68

    Plain functions

    Plain functions are just what you expect. You provide some arguments as input, the functionperforms some task, and depending on the function, some result is returned. Most functionsare 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 themath library, these objects similarlystore object methods (a.k.a. instance methods) as properties. One key difference, however, issyntax. 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 objectmethod 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 rstargument:

    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 totalmemory footprint of your application is kept to a minimum.

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

  • 7/28/2019 A Pi Reference

    16/68

    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 themvia garbage collection. It can even handle cyclic data structures. So most of the burdens ofmemory 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 isup to you to assign nil to these positions. This ensures that their corresponding memory willnot be locked and can be freed by the garbage collector.

    For display objects in the display hierarchy, the situation is slightly different. In addition tonil'ing references to a display object, you must explicitly it them from the display hierarchybefore 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 eachstatement (effectively a line of code), in Lua this is optional.

    Braces. You may be used to using { and } to dene variable scope. In Lua, you can do thisby 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 inwriting 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 tomax=(x>y?x:y) would bemax=(x>y and x or y). Beware that this

    idiom fails to work ifb is false.

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

    Multiple Assignment. Multiple assignments off

    er a convenient way to swap values. Thestatement x,y=y,x will swap x for y and vice versa.

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

  • 7/28/2019 A Pi Reference

    17/68

    Lua Standard Libraries

    Corona includes the same standard Lua libraries that are part of the Lua standard. Theselibraries 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 asmethods of its objects. This creates a logical grouping of functions and is Luas way of creatinga 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 tablemath 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. Forsecurity and performance reasons, several functions have been removed from the originalstandard 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 allits 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 species how to get the error position. With level1 (the default),the error position is where the error function was called. Level2 points the error to where thefunction that called error was called; and so on. Passing a level0 avoids the addition of errorposition information to the message.

    _GA global variable (not a function) that holds the global environment (that is, _G._G = _G). Luaitself 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

    http://www.lua.org/manual/5.1/manual.html#pdf-setfenvhttp://livepage.apple.com/http://livepage.apple.com/http://livepage.apple.com/http://www.lua.org/manual/5.1/manual.html#pdf-setfenvhttp://www.lua.org/manual/5.1/manual.html#pdf-setfenvhttp://livepage.apple.com/http://livepage.apple.com/
  • 7/28/2019 A Pi Reference

    18/68

    getfenv ([f])Returns the current environment in use by the function. f can be a Lua function or a numberthat species the function at that stack level: Level1 is the function calling getfenv. If the givenfunction is not a Lua function, or if f is 0, getfenv returns the global environment. The defaultfor 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 thegiven 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 secondargument is an index in this table. next returns the next index of the table and its associatedvalue. When called with nil as its second argument, next returns an initial index and itsassociated value. When called with the last index, or with nil in an empty table, next returnsnil. If the second argument is absent, then it is interpreted as nil. In particular, you can usenext(t) to check whether a table is empty.

    The order in which the indices are enumerated is not specied, even for numeric indices. ( Totraverse a table in numeric order, use a numerical for or the ipairs function.)

    The behavior of next is undened 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 clearexisting 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 keyvalue 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 insidefis not propagated; instead, pcall catches the error and returns a status code. Its rst result isthe 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 falseplus the error message.

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

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

    http://www.lua.org/manual/5.1/manual.html#pdf-string.formathttp://www.lua.org/manual/5.1/manual.html#pdf-nexthttp://www.lua.org/manual/5.1/manual.html#pdf-nexthttp://www.lua.org/manual/5.1/manual.html#pdf-nexthttp://www.lua.org/manual/5.1/manual.html#pdf-ipairshttp://www.lua.org/manual/5.1/manual.html#pdf-string.formathttp://www.lua.org/manual/5.1/manual.html#pdf-string.formathttp://www.lua.org/manual/5.1/manual.html#pdf-tostringhttp://www.lua.org/manual/5.1/manual.html#pdf-tostringhttp://www.lua.org/manual/5.1/manual.html#pdf-nexthttp://www.lua.org/manual/5.1/manual.html#pdf-nexthttp://www.lua.org/manual/5.1/manual.html#pdf-nexthttp://www.lua.org/manual/5.1/manual.html#pdf-nexthttp://www.lua.org/manual/5.1/manual.html#pdf-ipairshttp://www.lua.org/manual/5.1/manual.html#pdf-ipairs
  • 7/28/2019 A Pi Reference

    19/68

    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 atable, 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, indexmust 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 numberthat species the function at that stack level: Level1 is the function calling setfenv. setfenvreturns the given function.

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

    setmetatable (table, metatable)Sets the metatable for the given table. (You cannot change the metatable of other types fromLua, only fromC.) If metatable is nil, removes the metatable of the given table. If the originalmetatable 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 stringconvertible to a number, then tonumber returns this number; otherwise, it returns nil.

    An optional argument species the base to interpret the numeral. The base may be anyinteger between 2 and 36, inclusive. In bases above10, the letter 'A' (in either upper or lowercase) represents10, 'B' represents11, and so forth, with 'Z' representing 35. In base 10 (thedefault), 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. Forcomplete 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 eas 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 functionare "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

    http://www.lua.org/manual/5.1/manual.html#pdf-string.formathttp://www.lua.org/manual/5.1/manual.html#2.1http://www.lua.org/manual/5.1/manual.html#pdf-string.formathttp://www.lua.org/manual/5.1/manual.html#pdf-string.formathttp://www.lua.org/manual/5.1/manual.html#2.1http://www.lua.org/manual/5.1/manual.html#2.1
  • 7/28/2019 A Pi Reference

    20/68

    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, iis1 and j is the length of the list, as dened by the length operator (see 2.5.5).

    Modules

    Corona supports Luas module functionality for creating and loading external libraries.Currently, two example libraries are shipped with the SDK: ui.lua (for creating rolloverbuttons) and sprite.lua (for creating animated sprites, or movieclips).

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

    You can also create Lua modules of your own, which is helpful for organizing large projectsinto 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 projectsmain.luale:

    module(..., package.seeall)

    -- Declare the functions you want in your module

    function hello() print ("Hello, module")end

    The rst line should be entered as shown here, including the three dots. Modules should besaved with a .luale 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 formatmodname.functionname().

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

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

    http://www.lua.org/manual/5.1/manual.html#2.5.5http://www.lua.org/manual/5.1/manual.html#2.5.5http://www.lua.org/manual/5.1/manual.html#2.5.5
  • 7/28/2019 A Pi Reference

    21/68

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

    local 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 ofpackage.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 minuslast 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 todetermine 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 defaultconguration for package.loaders.

    First, require queries package.preload[modname]. If it has a value, this value (which should bea 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 theloader 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 ofpackage.loaded[modname].

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

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

  • 7/28/2019 A Pi Reference

    22/68

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

    package.loaders

    A 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 ofthese searchers in ascending order, with the module name (the argument given to require) asits sole parameter. The function may return another function (the module loader) or a stringexplaining 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 thesame 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 functionmodule.

    String Manipulation

    This library provides generic functions for string manipulation, such as nding and extractingsubstrings, and pattern matching. When indexing a string in Lua, the rst character is atposition1 (not at0, as in C). Indices are allowed to be negative and are interpreted as indexingbackwards, 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 stringfunctions 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 iis1; the default value for j isi.

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

    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 theindices ofs where this occurrence starts and ends; otherwise, it returns nil. A third, optionalnumerical argument init species where to start the search; its default value is1 and can be

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

  • 7/28/2019 A Pi Reference

    23/68

    negative. A value offalse as a fourth, optional argument plain turns offthe pattern matchingfacilities, so the function does a plain "nd substring" operation, with no characters in patternbeing 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 descriptiongiven in its rst argument (which must be a string). The format string follows the same rules asthe printf family of standard Cfunctions. The only differences are that the options/modiers *,l, L, n, p, and h are not supported and that there is an extra option, q. The q option formats astring in a form suitable to be safely read back by the Lua interpreter: the string is writtenbetween double quotes, and all double quotes, newlines, embedded zeros, and backslashes inthe 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 sexpect a string.

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

    string.gmatch (s, pattern)Returns an iterator function that, each time it is called, returns the next captures from patternover string s. If pattern species 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 allpairs 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

  • 7/28/2019 A Pi Reference

    24/68

    For this function, a '^' at the start of a pattern does not work as an anchor, as this wouldprevent 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 beenreplaced by a replacement string specied 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 escapecharacter: any sequence in repl of the form %n, with n between 1 and 9, stands for the value ofthe n-th captured substring (see below). The sequence %0 stands for the whole match. Thesequence %% stands for a single%.

    If repl is a table, then the table is queried for every match, using the rst capture as the key; ifthe pattern species 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 capturedsubstrings passed as arguments, in order; if the pattern species no captures, then the wholematch 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 isused as the replacement string; otherwise, if it is false or nil, then there is no replacement (thatis, 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 arecounted, so "a\000bc\000" has length 5.

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

  • 7/28/2019 A Pi Reference

    25/68

    string.lower (s)Receives a string and returns a copy of this string with all uppercase letters changed tolowercase. All other characters are left unchanged. The denition of what an uppercase letteris 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 thecaptures from the pattern; otherwise it returns nil. If pattern species no captures, then thewhole match is returned. A third, optional numerical argument init species where to start thesearch; its default value is1 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). Inparticular, the call string.sub(s,1,j) returns a prex of s with length j, and string.sub(s, -i) returnsa suffix of s with length i.

    string.upper (s)Receives a string and returns a copy of this string with all lowercase letters changed touppercase. All other characters are left unchanged. The denition of what a lowercase letter isdepends on the current locale.

    Patterns

    Character Class:

    A character class is used to represent a set of characters. The following combinations areallowed 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

  • 7/28/2019 A Pi Reference

    26/68

    %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 thestandard 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 specied by separating the end characters of the range with a '-'. All classes %x describedabove can also be used as components in set. All other characters in set representthemselves. For example, [%w_] (or [_%w]) represents all alphanumeric characters plus theunderscore, [0-7] represents the octal digits, and [0-7%l%-] represents the octal digits plusthe lowercase letters plus the '-' character. The interaction between ranges and classes isnot dened. 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 denitions of letter, space, and other character groups depend on the current locale. Inparticular, the class [a-z] may not be equivalent to %l.

    Pattern Item:Apattern 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 inthe 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 inthe class. These repetition items will always match the longest possible sequence;

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

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

    %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 withx,

    end withy, and where the x and y are balanced. This means that, if one reads the string fromleft to right, counting +1 for an x and -1 for a y, the ending y is the rst y where the countreaches 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 matchat the beginning of the subject string. A '$' at the end of a pattern anchors the match at theend of the subject string. At other positions, '^' and '$' have no special meaning and representthemselves.

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

  • 7/28/2019 A Pi Reference

    27/68

    Captures:A pattern can contain sub-patterns enclosed in parentheses; they describe captures. When amatch 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 thepattern "(a*(.)%w(%s*))", the part of the string matching "a*(.)%w(%s*)" is stored as the rstcapture (and therefore has number1); the character matching "." is captured with number2,

    and the part matching "%s*" has number3.

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

    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 thesefunctions, when we talk about the "length" of a table we mean the result of the lengthoperator.

    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 defaultfor 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 nopositive numerical indices. (To do its job this function does a linear traversal of the wholetable.)

    table.remove (table [, pos])Removes from table the element at position pos, shifting down other elements to close thespace, 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 oftable t.

    table.sort (table [, comp])Sorts table elements in a given order, in-place, from table[1] to table[n], where n is the lengthof the table. If comp is given, then it must be a function that receives two table elements, andreturns false when the rst is less than the second (so that not comp(a[i+1],a[i]) will be falseafter 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

  • 7/28/2019 A Pi Reference

    28/68

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

    Mathematical Functions

    This library is an interface to the standard Cmath library. It provides all its functions inside the

    tablemath.

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

  • 7/28/2019 A Pi Reference

    29/68

    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 providedby ANSIC. (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-randominteger in the range [1, m]. When called with two integer numbers m and n, math.randomreturns 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 sequencesof 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

  • 7/28/2019 A Pi Reference

    30/68

    Input and Output Facilities

    The I/O library provides two different styles for le manipulation. The rst one implicitlyoperates on a default le object; that is, there are operations to set a default input le and adefault 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 operationsare supplied as methods of the le descriptor.

    The table io also provides three predened 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 asecond result and a system-dependent error code as a third result) and some value differentfrom 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 found

    local 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

    http://localhost/var/www/apps/conversion/tmp/scratch_2/%23io.openhttp://localhost/var/www/apps/conversion/tmp/scratch_2/%23io.open
  • 7/28/2019 A Pi Reference

    31/68

    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 thedefault 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 iscalled, 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 ofle, it returnsnil (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 specied in the string mode. It returns a new lehandle, 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 ofle.

    The mode string can also have a 'b' at the end, which is needed in some systems to open thele in binary mode. This string is exactly what is used in the standardC 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 readdata 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

    http://localhost/var/www/apps/conversion/tmp/scratch_2/%23io.inputhttp://localhost/var/www/apps/conversion/tmp/scratch_2/%23io.inputhttp://localhost/var/www/apps/conversion/tmp/scratch_2/%23io.inputhttp://localhost/var/www/apps/conversion/tmp/scratch_2/%23io.inputhttp://localhost/var/www/apps/conversion/tmp/scratch_2/%23io.inputhttp://localhost/var/www/apps/conversion/tmp/scratch_2/%23io.inputhttp://localhost/var/www/apps/conversion/tmp/scratch_2/%23io.input
  • 7/28/2019 A Pi Reference

    32/68

    io.tmple ()Returns a handle for a temporary le. This le is opened in update mode and it is automaticallyremoved 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 ofcolon ':' 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 whenthe 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 datawith the specied format. When called without formats, it uses a default format that reads theentire 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 ofle, it returns the emptystring.

    "*l": reads the next line (skipping the end of line), returning nil on end of

    le. This is the defaultformat.

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

    le:seek ([whence] [, offset])Sets and gets the le position, measured from the beginning of the le, to the position givenby offset plus a base specied by the string whence, as follows:

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

  • 7/28/2019 A Pi Reference

    33/68

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

    "cur": base is current position;

    "end": base is end ofle;

    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 thecurrent le position, without changing it; the call le:seek("set") sets the position to thebeginning of the le (and returns 0); and the call le:seek("end") sets the position to the end ofthe 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 fromsome special les (such as a terminal device).

    For the last two cases, size species the size ofthe buffer, in bytes. The default is anappropriate size.

    le:write (...)Writes the value of each of its arguments to the le. The arguments must be strings ornumbers. 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 stringformat.

    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 thisoptional 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 is1), 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 samerules as the Cfunction strftime.

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

    http://www.lua.org/manual/5.1/manual.html#pdf-os.timehttp://www.lua.org/manual/5.1/manual.html#pdf-os.timehttp://www.lua.org/manual/5.1/manual.html#pdf-tostringhttp://www.lua.org/manual/5.1/manual.html#pdf-string.formathttp://www.lua.org/manual/5.1/manual.html#pdf-string.formathttp://www.lua.org/manual/5.1/manual.html#pdf-string.formathttp://www.lua.org/manual/5.1/manual.html#pdf-io.flushhttp://www.lua.org/manual/5.1/manual.html#pdf-os.timehttp://www.lua.org/manual/5.1/manual.html#pdf-os.timehttp://www.lua.org/manual/5.1/manual.html#pdf-string.formathttp://www.lua.org/manual/5.1/manual.html#pdf-string.formathttp://www.lua.org/manual/5.1/manual.html#pdf-tostringhttp://www.lua.org/manual/5.1/manual.html#pdf-tostringhttp://www.lua.org/manual/5.1/manual.html#pdf-io.flushhttp://www.lua.org/manual/5.1/manual.html#pdf-io.flush
  • 7/28/2019 A Pi Reference

    34/68

    When called without arguments, date returns a reasonable date and time representation thatdepends on the host system and on the current locale (that is, os.date() is equivalent toos.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 Cfunction exit, with an optional code, to terminate the host program. The defaultvalue 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. Ifthis 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, plusa string describing the error.

    os.time ([table])Returns the current time when called without arguments, or a time representing the date andtime specied by the given table. This table must have elds year, month, and day, and mayhave 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 starttime (the "epoch"). In other systems, the meaning is not specied, and the number returned bytime can be used only as an argument to date and difftime.

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

    http://www.lua.org/manual/5.1/manual.html#pdf-os.datehttp://www.lua.org/manual/5.1/manual.html#pdf-os.date
  • 7/28/2019 A Pi Reference

    35/68

    Corona Core Libraries

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

    The following are Coronas core libraries. These are built-in and loaded automatically when theapplication launches:

    display provides all routines for creating display objects.

    transition simplies the animation of display objects, simplifying the process of creatingbasic tweens.

    easing is a collection of interpolation functions that can be used in conjunction with thetransition 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 haveto explicitly load them using require.

    Runtime

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

    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 andDrawing chapter of the Corona SDK Applications Programming Guide.

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

    Creating DisplayObjects

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

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

  • 7/28/2019 A Pi Reference

    36/68

    As explained in the Display Objects chapter, DisplayObjects share some common propertiesand methods. In addition, there are specic 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 tothis 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 atthe 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 youdon'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 dimensionswidth 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; thereference point is initialized to this local origin. By default, there is no ll or stroke color.

    display.newRoundedRect( left, top, width, height, cornerRadius )

    Creates awidth by height rounded rectangle with the top-left corner at (left, top); returnsa 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 isinitialized 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 species the font to use. The local origin is at the center of the text; thereference 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.statusBarHeightA read-only property representing the height of the status bar in pixels

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

  • 7/28/2019 A Pi Reference

    37/68

    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. IfsaveToAlbumis false, then it adds the image to yourdevice'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 imageis 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 argumentmode 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 moreproperties of an object (e.g. a display object) over a specied duration.

    transition.to( target, params )

    Returns a tween that animates properties in the display object target over time. The nal

    property values are specied in the params table. To customize the tween, you can optionally

    specify the following non-animating properties in params:

    params.time species the duration of the transition in milliseconds. By default, theduration is 500 ms (0.5 seconds).

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

    params.delay species the delay (none by default) before the tween begins.

    params.delta is a boolean specifying whether non-control parameters are interpreted asnal 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 targetinstead of an event.

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

  • 7/28/2019 A Pi Reference

    38/68

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

    The transition library eliminates the need for manually animating objects. Compare thefollowing 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 listenerRuntime:removeEventListener(

    "enterFrame", fadeOut )

    end

    end

    -- Add listener to begin animation

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

  • 7/28/2019 A Pi Reference

    39/68

    You can create your own easing function to interpolate between a start and a nal value. Thearguments of the function are dened 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 thanimmediately. 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. Iflistener is a table, it must

    have a timer method because timer events are sent to the listener. An optional parameter

    iterations species the number of times listener is invoked. By default, it is 1; pass 0 ifyou 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

    end

    end

    -- Register to call t's timer method an infinite number of times

    timer.performWithDelay( 1000, t, 0 )

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

  • 7/28/2019 A Pi Reference

    40/68

    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 bepassed to media.playEventSound. Currently, the sound le must be in the applicationresources directory (see system.ResourceDirectory).

    media.playEventSound( sound )

    Plays an event sound (1-3 seconds). The argumentsound can be either an event sound id or alename for the event sound. Recommended for short sounds, especially to avoid animation

    hiccups. Returns the same thing asmedia.newEventSound.

    local soundID = media.newEventSound( "beep.caf" )

    local playBeep = function() media.playEventSound( soundID )end

    timer.performWithDelay( 7500, playBeep, 0 )

    The following functions should be used to play longer duration sound. You can only have onesound 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 .aifle.

    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

  • 7/28/2019 A Pi Reference

    41/68

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

    For longer sounds, usemedia.playSound() to play .mp3les.

    Video

    media.playVideo( path [, baseSource ], showControls, listener )

    Plays the path in a device-specic popup media player. The optional parameter baseSource

    controls how path is interpreted and can be one of the system-dened 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. IfshowControls is false, thenthe user can adjust playback, e.g. start, stop, seek, etc. Pass a listener to get notied when thevideo 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" )

    end

    media.playVideo( "Movie.m4v", true, onComplete )

    The listener can be either a function listener or a table listener. Iflistener 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 movieles with the .mov, .mp4, .m4v, and .3gplename extensions and using the following compression standards:

    H.264 Baseline Prole Level 3.0 video, up to 640 x 480 at 30 fps. Note: B frames are notsupported in the Baseline prole.

    MPEG-4 Part 2 video (Simple Prole)

    Camera and Photo Library

    media.show( imageSource, listener )Opens a platform-specic interface. This function returns immediately so the calling code willcontinue 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

  • 7/28/2019 A Pi Reference

    42/68

    media.Camera

    media.SavedPhotosAlbum

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

    local onComplete = function(event)

    local photo = event.target

    print( "photo w,h = " .. photo.width .. "," .. photo.height )

    end

    media.show( media.Camera, onComplete )

    The listener can be either a function listener or a table listener. Iflistener is a table, it must

    have a completion method. The event dispatched to the listener will be a completion eventwith the following additional properties:

    event.targetis 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-specic activity indicator. Touch events are ignored while theindicator 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 apprunning on the iPhone.

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

  • 7/28/2019 A Pi Reference

    43/68

    Alert

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

    The strings title andmessage 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 twobuttons, for example OK and Cancel.

    The listener is notied when a user presses any button in the alert box, and it can assign anaction 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. Iflistener

    is a table, it must have a completion method. The event dispatched to the listener will be acompletion event. It will contain the following additional properties:

    event.action indicates how the alert was dismissed


Recommended