# Lua

Tables, strings, and math

[Reference](index.md)

<a id="section-Guides"></a>

## Guides

<a id="How-Codea-Works"></a>

### How Codea Works

Codea calls functions in your project to draw the screen and respond to touches, keys, and other events.

A new project starts with a `Main.lua` tab containing these functions:

```lua
-- Called once at the beginning
function setup()
   x = WIDTH/2
   y = HEIGHT/2
end

-- Called every frame
function draw()
   background(128)
   style.push().fill(color.red).stroke(255).strokeWidth(5)
   ellipse(x, y, 100, 100)
end

-- Called when a touch is detected or updated
function touched(touch)
   if touch.began or touch.changed then
      x = touch.x
      y = touch.y
   end
end
```

Press Play to run the project. Codea calls `setup()` once, then `draw()` each frame. It calls `touched(touch)` as touches begin, move, and end, including mouse clicks and drags.

## setup()

Use `setup()` to load images, create objects, and set starting values before the first frame.

## draw()

Use `draw()` to draw the screen and move objects each frame.

## touched(touch)

Use `touched(touch)` to respond to taps and drags. The `touch` value tells you the position and whether the touch began, moved, or ended.

## update(dt)

Use `update(dt)` to keep movement and game logic separate from drawing. `dt` is the time in seconds since the last frame, also available as `time.delta`.

## fixedUpdate(dt)

Use `fixedUpdate(dt)` for physics or other simulations that need evenly spaced time steps. Codea calls it a fixed number of times per second, independently of drawing. `dt` is the same as `time.fixedDelta`.

## keyPressed(keyPress)

Called when a key on a hardware keyboard goes down. `keyPress.keyCode` identifies the key and `keyPress.characters` holds the text it typed. It is not called while a user interface text field has focus

```lua
function keyPressed(keyPress)
   if keyPress.keyCode == key.space then
      print("space")
   else
      print("typed", keyPress.characters)
   end
end
```

## keyReleased(keyPress)

Called when a key on a hardware keyboard comes back up. It receives the same kind of `keyPress` as `keyPressed()`

```lua
function keyReleased(keyPress)
   if keyPress.keyCode == key.space then
      print("space released")
   end
end
```

## scroll(gesture)

Called when the user scrolls with a trackpad or mouse wheel. `gesture.delta` is the scroll movement since the last call and `gesture.location` is the pointer position

```lua
function scroll(gesture)
   y = y + gesture.delta.y
end
```

## hover(gesture)

Called when a mouse or trackpad pointer moves over the viewer with no button held. `gesture.location` is the pointer position

```lua
function hover(gesture)
   x = gesture.location.x
   y = gesture.location.y
end
```

## Learning Lua by changing a program

This project introduces strings, variables, `nil`, and `if/elseif/else`. Read the comments and watch the console output. Try changing `foo` to choose a different branch.

#### Learning Lua by changing a program

[Download project](data/downloads/Learning-Lua-by-changing-a-program-a7ab7e17ce13.zip) — Open in Codea to run this example.

```lua
-- How to Codea
-- Hello World and Lua

-- This is a comment. Anything beginning with '--' will be ignored by the
-- compiler

-- Functions

-- This is a function in Lua, everything from 'function' until the matching 'end' keyword
-- is run together. Codea calls the setup() function when your program begins
function setup()

    -- There are special built-in functions that you can call yourself
    -- Start with the name of the function ('print' in this example) followed by brackets '()'
    -- In this case print takes one 'argument' which is a string (which contains a series of letters)
    -- Strings are contained within quotation marks, Lua supports both single and double quotation marks
    -- but you need to make sure that the begin and end quote match or you will get an error
    print("Hello World!")

    -- You can change the argument to whatever string you want and Codea will print
    -- it in the output panel for you
    print("Hello Codea!")

    -- Locals and Global variables

    -- You can create variables to store data for you and use that to control your program
    -- Lua supports local and global variables. A local variable exists only in the scope
    -- where you create it. A function is a type of scope. We'll cover scopes more later
    local x = "Hello Local Variable!"
    print(x)

    -- The above code creates a local variable (named: x) and uses it as an argument for the print
    -- function. This variable is local and therefore only exists in the scope of this function

    g = "Hello Global Variable!"
    print(g)

    -- The above code creates a global variable (named: g) and does the same thing. The only
    -- difference is that now g exists everywhere in the program, and will continue to exist
    -- outside the scope of this function

    -- Using nil

    -- In Lua whenever trying to access a variable that does not exist, the value nil will
    -- be returned. Nil represents nothing and is useful in many ways. You can also assign
    -- nil to a variable to destroy it

    g = nil -- destroy g
    print(g)

    -- Flow Control

    -- In order to make a program do what we want, we need to compare variables and execute
    -- code. This is called flow control and is a key cornerstone of programming

    -- To conditionally execute some code we use an 'if' statement. The 'if' keyword is
    -- followed by a condition, which evaluates the logical truth of something.
    -- In this case we use 'foo == 1', which mean check if the variable named 'foo' is equal
    -- to the value 1. This is always followed by 'then' and subsequently ended with the 'end'
    -- keyword. Everything between 'then' and 'end' is executed if the condition is true
    local foo = 42

    if foo == 42 then
        print("Foo is equal to 42!")
    end

    -- We can also chain together multiple branches, including 'else' and 'elseif' which execute
    -- when the condition is false, or some other condition is true when the previous one isn't

    foo = 21

    if foo == 42 then
        print("Foo is equal to 42!")
    elseif foo == 21 then
        print("Foo is equal to 21!")
    else
        print("Foo is equal to something else?!?")
    end

end

function draw()
    background(42)
    style.fill(255).fontSize(24).textAlign(CENTER | MIDDLE)
    text("Hello Lua! Explore the commented source.", WIDTH/2, HEIGHT/2, WIDTH - 40)
end

function touched(touch)
end

```

<a id="section-Language-Basics"></a>

## Language Basics

<a id="Iterating-with-For-Loops"></a>

### Iterating with For Loops

Use a **for loop** to repeat code for a range of numbers or each item in a table.

This loop prints the numbers 1 to 10:

```lua
-- Iterate from 1 to 10
for i = 1, 10 do
  print( i )
end
```

Use `ipairs` to visit numbered items in order, starting at 1. It stops at the first missing item:

```lua
-- Iterate over an array named 'arr'
arr = { 3, 2, 1 }

for i,v in ipairs(arr) do
  print( "arr["..i.."] = "..v )
end

-- Prints:
--  arr[1] = 3
--  arr[2] = 2
--  arr[3] = 1
```

Use `pairs` to visit every key and value, including named keys. The order is not guaranteed:

```lua
-- Iterate over a table named 'tab'
tab = { x = 3, y = "string", z = 1 }

for key,value in pairs(tab) do
  print( "tab."..key.." = "..value )
end

-- Prints:
--  tab.y = string
--  tab.x = 3
--  tab.z = 1
```

<a id="Making-Decisions-with-Conditionals"></a>

### Making Decisions with Conditionals

Use `if`, `elseif`, and `else` to choose which code runs based on a condition:

```lua
-- Check if x is equal to 10
if x == 10 then
  print( "x equals 10" )
end

-- else and elseif
if x == 10 then
  print( "x is 10" )
elseif x == 5 then
  print( "x is 5" )
else
  print( "x is something else: "..x )
end

-- Checking multiple values
if x == 10 and y < 5 then
  print( "x is 10 and y is less than 5" )
elseif x == 5 or y == 3 then
  print( "x is 5 or y is 3" )
else
  print( "x is "..x.." and y is "..y )
end
```

<a id="Repeating-with-While-Loops"></a>

### Repeating with While Loops

A `while` loop runs while its condition is true. A `repeat` loop runs until its condition becomes true, checking after each repetition. Use them when you do not know in advance how many repetitions you need.

```lua
-- simple while loop. The condition is evaluated at the beginning of the loop. The loop will never get executed if the condition is false at the beginning of the loop.
while i<=5 do
  print(i)
  i=i+1
end

-- repeat loop. The condition is evaluated at the end of the loop, so the code always gets executed at least once
repeat
  print(i)
  i=i+1
until i>5

-- break statement: break exits a loop and continues program flow with the statement immediately following the end or until condition
while true do
  print(i)
  i=i+1
  if i>5 then
      break
  end
end
```

<a id="Adding-Type-Annotations"></a>

### Adding Type Annotations

Type annotations tell Codea what a variable contains so it can offer better code completions.

Start a comment with three dashes (`---`). Codea suggests an annotation for the assignment or function on the next line. You can also write `--- variableName: variableType` yourself.

When using annotations for Objective-C types, this will add Objective-C properties and methods auto-completion to your variables.

```lua
-- method annotation
--- makeBox Creates a box body
--- pos: vec2, bottom-left position of the box
--- size: vec2, size of the box
function createBoxBody(pos, size)

-- variable annotation
--- textView: objc.UITextView
textView = objc.UITextView()
```

<a id="section-Language"></a>

## Language

<a id="print"></a>

### print(...)

```lua
print( ... )
```

Prints values to the output console.

#### Parameters

- **...** (any): values to print

<a id="warn"></a>

### warn(msg, ...)

```lua
warn( "player health is negative" )

-- Repeats are suppressed by default, so this shows a single warning
for i = 1, 100 do
    warn( "this appears only once" )
end

-- Opt in to seeing every occurrence
warn( "@always" )
warn( "@once" )

warn( "@off" )
warn( "this is not shown" )
warn( "@on" )

-- Arguments are concatenated, so this emits one warning reading "x = 42"
warn( "x = ", tostring( 42 ) )
```

Emits a warning to the output console, composed by concatenating all its arguments
(which must be strings). Warnings appear alongside `print` output, marked as
warnings.

A one-piece message starting with `@` is a *control message*: it changes how the
warning system behaves instead of being displayed. Codea recognizes four:

Codea differs from standard Lua in two ways, both chosen so that warnings behave the
way they always have in Codea:

- Warnings are **on** by default, so there is no need to call `warn( "@on" )`
before your first warning.
- Repeated messages are suppressed by default, as if `warn( "@once" )` were already
in effect. This keeps a warning inside `draw()` from flooding the console. Use
`warn( "@always" )` when you want every occurrence.

Unknown control messages are ignored. A control message must be a single argument, so
`warn( "@of", "f" )` emits a warning reading `@off` rather than turning warnings
off.

emit a warning to the output console

#### Parameters

- **msg** (string): the warning message, or one of the control messages above
- **...** (string): additional strings, concatenated onto msg

<a id="ipairs"></a>

### ipairs(table)

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

-- This will iterate over the pairs:
--   (1,t[1]), (2,t[2]), ...
```

ipairs can be used to iterate over a table sequentially, starting from the index 1 and continuing until the first integer key absent from the table. Returns three values: an iterator function, the table, and 0.

#### Parameters

- **table** (table): table to iterate over

#### Returns

- **function**: Returns three values: an iterator function, the table, and 0
- **table**: 
- **integer**: 

<a id="pairs"></a>

### pairs(table)

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

-- This will iterate over all key-value
-- pairs in table t
```

pairs can be used to iterate over a tables key-value pairs. Returns three values: the next function, the table t, and nil.

#### Parameters

- **table** (table): table to iterate over

#### Returns

- **function**: Returns three values: the next function, the table t, and nil
- **table**: 
- **nil**: 

<a id="section-Tables"></a>

## Tables

<a id="table.concat"></a>

### table.concat(table, sep)

```lua
table.concat( table )
table.concat( table, sep )
table.concat( table, sep, i )
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.

#### Parameters

- **table** (table): table to concatenate
- **sep** (string): separator string

#### Returns

- **string**: A string of the elements in table concatenated with each other, separated by sep

<a id="table.move"></a>

### table.move(a1, f, e, t, a2)

```lua
table.move( a1, f, e, t )
table.move( a1, f, e, t, a2 )
```

Moves elements from table a1 into table a2. This function performs the equivalent to the multiple assignment: a2[t], … = a1[f], …, a1[e]. The default value for a2 is a1. The destination range can overlap with the source range. Index f must be positive.

#### Parameters

- **a1** (table): table to move elements from
- **f** (integer): starting index in table to move from
- **e** (integer): ending index in table to move from
- **t** (integer): starting index in table to move into
- **a2** (table): table to move elements into (defaults to a1)

<a id="table.insert"></a>

### table.insert(table, pos, value)

```lua
table.insert( table, value )
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.

#### Parameters

- **table** (table): table to insert into
- **pos** (integer): int, position to inset
- **value** (any): value to insert

<a id="table.remove"></a>

### table.remove(table, pos)

```lua
table.remove( 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.

#### Parameters

- **table** (table): table to insert into
- **pos** (integer): int, position of value to remove

#### Returns

- **value**: Value of the removed element

<a id="table.pack"></a>

### table.pack(...)

```lua
table.pack( ... )
```

Returns a new table with all parameters stored into keys 1, 2, etc. and with a field “n” with the total number of parameters. Note that the resulting table may not be a sequence.

#### Parameters

- **...** (any): arguments to pack into table

#### Returns

- **table**: table with all parameters packed

<a id="table.unpack"></a>

### table.unpack(list)

```lua
table.unpack( list )
```

Returns the elements from the given list.

#### Parameters

- **list** (table): list to unpack

#### Returns

- **value**: elements unpacked from list

<a id="table.sort"></a>

### table.sort(table)

```lua
table.sort( table )
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 true when the first is less than the second (so that not comp(a[i+1],a[i]) will be true after the sort). If comp is not given, then the standard Lua operator < is used instead.

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

#### Parameters

- **table** (table): the table to sort

<a id="section-Strings"></a>

## Strings

<a id="string.byte"></a>

### string.byte(s, i, j)

```lua
string.byte( s )
string.byte( s, i )
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. These indices are corrected following the same rules of string.sub.

#### Parameters

- **s** (string): string to use
- **i** (integer): first index, defaults to 1
- **j** (integer): last index, defaults to i

#### Returns

- **value**: The internal numerical codes for characters s[i] up to s[j]

<a id="string.char"></a>

### string.char(...)

```lua
string.char( ... )
```

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.

#### Parameters

- **...** (integer): a variable number of numerical codes

#### Returns

- **string**: String composed of characters equal to the numerical codes used as arguments

<a id="string.dump"></a>

### string.dump(function)

```lua
string.dump( function )
string.dump( function, strip )
```

Returns a string containing a binary representation (a *binary chunk*) of the given function, so that a later load on this string returns a copy of the function (with new upvalues). If strip is a true value, the binary representation is created without debug information about the function (local variable names, lines, etc).

#### Parameters

- **function** (function): a function to convert to binary string

#### Returns

- **string**: Binary string representation of the specified function

<a id="string.find"></a>

### string.find(s, pattern)

```lua
string.find( s, pattern )
string.find( s, pattern, init )
string.find( s, pattern, init, plain )
```

Looks for the first match of pattern in the string s. If it finds a match, then string.find() returns the indices of s where the occurrence starts and ends; otherwise, it returns nil. A third, optional numerical argument init specifies where to start the search, its default value is 1 and can be negative. A value of true as the fourth optional argument plain turns off the pattern matching facilities so the function performs a plain “find 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.

#### Parameters

- **s** (string): string to search in
- **pattern** (string): pattern to look for

#### Returns

- **value**: The start and end indices of the match, or nil if no match. If the pattern has captures then captured values are also returned after the indices

<a id="string.format"></a>

### string.format(formatstring, ...)

```lua
string.format( formatstring, ... )
```

Returns a formatted version of its variable arguments following the description given in the first argument, which must be a string. The format string follows the same rules as the printf family of standard C functions. The only difference are that the options/modifiers *, 1, 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, for example all double quotes, newlines, embedded zeros and backslashes will be escaped when written.

#### Parameters

- **formatstring** (string): string defining the format
- **...** (any): Additional values accepted by this function; each must match the format or operation.

#### Returns

- **string**: A formatted string

<a id="string.len"></a>

### string.len(s)

```lua
string.len( s )
```

Receives a string and returns its length. The empty string “” has length 0.

#### Parameters

- **s** (string): get the length of this string

#### Returns

- **string**: Length of string s

<a id="string.gmatch"></a>

### string.gmatch(s, pattern)

```lua
string.gmatch( s, pattern )
```

Returns an iterator function that, each time it is called, returns the next captures from pattern (see **Patterns Overview**) over the string s. If pattern specifies no captures, then the whole match is produced in each call.

#### Parameters

- **s** (string): string to search
- **pattern** (string): pattern to match

#### Returns

- **string**: Iterator function over matches of pattern within the string

<a id="string.gsub"></a>

### string.gsub(s, pattern, repl)

```lua
string.gsub( s, pattern, repl )
string.gsub( s, pattern, repl, n )
```

Returns a copy of s in which all (or the first n, if given) occurrences of the pattern (see **Patterns Overview**) have been replaced by a replacement string specified 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. The name gsub comes from *Global SUBstitution*.

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 %d, with d between 1 and 9, stands for the value of the d-th captured substring. 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 first capture 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.

In any case, if the pattern specifies no captures, then it behaves as if the whole pattern was inside a capture.

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

#### Parameters

- **s** (string): string to substitute
- **pattern** (string): pattern to match
- **repl** (string or table or function): table or function, replacement parameter

#### Returns

- **number**: Returns a copy of s with substitutions made, as well as the number of matches

<a id="string.lower"></a>

### string.lower(s)

```lua
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.

#### Parameters

- **s** (string): get a lowercase version of this string

#### Returns

- **string**: Lowercase version of string s

<a id="string.upper"></a>

### string.upper(s)

```lua
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.

#### Parameters

- **s** (string): get an uppercase version of this string

#### Returns

- **string**: Uppercase version of string s

<a id="string.match"></a>

### string.match(s, pattern)

```lua
string.match( s, pattern )
string.match( s, pattern, init )
```

Looks for the first match of pattern in the string s. If it finds one then string.match() returns the captures from the pattern, otherwise it returns nil. If pattern specifies no captures, then the whole match is returned. A third optional numerical argument init specifies where to start the search. Its default is 1 and can be negative.

#### Parameters

- **s** (string): string to search
- **pattern** (string): pattern to match

#### Returns

- **string**: Captures from the first match of pattern in string s, or nil if none were found

<a id="string.rep"></a>

### string.rep(s, n)

```lua
string.rep( s, n )
```

Returns a string that is the concatenation of n copies of the string s.

#### Parameters

- **s** (string): string to replicate
- **n** (integer): int, number of times to replicate the string

#### Returns

- **string**: n concatenations of string s

<a id="string.reverse"></a>

### string.reverse(s)

```lua
string.reverse( s )
```

This function returns the string s reversed.

#### Parameters

- **s** (string): string to reverse

#### Returns

- **value**: s reversed

<a id="string.sub"></a>

### string.sub(s, i, j)

```lua
string.sub( s, i )
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 prefix of s with length j, and string.sub(s, -i) returns a suffix of s with length i.

#### Parameters

- **s** (string): find substring of this string
- **i** (integer): int, starting index
- **j** (integer): int, ending index

#### Returns

- **string**: Substring of string s

<a id="string.pack"></a>

### string.pack(fmt, v1, v2, ...)

```lua
string.pack( fmt, v1, v2, ... )
```

Returns a binary string containing the values v1, v2, etc. packed (that is, serialized in binary form) according to the format string fmt.

#### Parameters

- **fmt** (string): format string specifying binary format
- **v1** (any): First value to pack according to the format string.
- **v2** (any): Second value to pack according to the format string.
- **...** (any): arguments to pack

#### Returns

- **string**: Values packed into binary string

<a id="string.packsize"></a>

### string.packsize(fmt)

```lua
string.packsize( fmt )
```

Returns the size of a string resulting from string.pack with the given format. The format string cannot have the variable-length options ‘s’ or ‘z’

#### Parameters

- **fmt** (string): format string specifying binary format

#### Returns

- **string**: Size of string packed with the given format

<a id="string.unpack"></a>

### string.unpack(fmt, s)

```lua
string.unpack( fmt, s )
string.unpack( fmt, s, pos )
```

Returns the values packed in string s according to the format string fmt. An optional pos marks where to start reading in s (default is 1). After the read values, this function also returns the index of the first unread byte in s.

#### Parameters

- **fmt** (string): format string specifying binary format
- **s** (string): string to unpack

#### Returns

- **value**: The values packed in s

<a id="Matching-String-Patterns"></a>

### Matching String Patterns

Patterns in Lua are described by regular strings, which are interpreted as patterns by the
pattern-matching functions string.find, string.gmatch, string.gsub, and string.match.
This section describes the syntax and the meaning (that is, what they match) of these strings.

**Character Class**

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

```lua
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.
%g: represents all printable characters except space.
%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.
%x: represents all hexadecimal digits.
%x: (where x is any non-alphanumeric character)
  represents the character x.
  This is the standard way to escape
  the magic characters. Any non-alphanumeric
  character (including all punctuations, even
  the non-magical) 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 specified
  by separating the end characters of the
  range, in ascending order, 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.
[^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 definitions 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:

```lua
- a single character class, which matches
any single character in the class;
- a single character class followed by '*',
which matches zero 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 one 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 zero 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 zero or one occurrence of
a character in the class. It always
matches one occurrence if possible;
- %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 first
y where the count reaches 0.
For instance, the item %b() matches
expressions with balanced parentheses.
- %f[set], a frontier pattern; such item
matches an empty string at any position
such that the next character belongs to
set and the previous character does not
belong to set. The set set is interpreted
as previously described. The beginning
and the end of the subject are handled
as if they were the character '\0'.
```

**Pattern**

A pattern is a sequence of pattern items. A caret ‘^’ 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.

**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 first 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 “flaaap”, there will be two captures: 3 and 5.

<a id="section-Math"></a>

## Math

<a id="math"></a>

### math

<a id="math.abs"></a>

### math.abs(value)

```lua
math.abs( value )
```

This function returns the absolute value of value. For example, math.abs(-5) returns 5.

#### Parameters

- **value** (number): int or float, the number to get the absolute value of

#### Returns

- **value**: The absolute value of value

<a id="math.acos"></a>

### math.acos(value)

```lua
math.acos( value )
```

This function returns the arc cosine of value in radians

#### Parameters

- **value** (number): int or float, compute the arc cosine of this number

#### Returns

- **value**: The arc cosine of value in radians

<a id="math.asin"></a>

### math.asin(value)

```lua
math.asin( value )
```

This function returns the arc sine of value in radians

#### Parameters

- **value** (number): int or float, compute the arc sine of this number

#### Returns

- **value**: The arc sine of value in radians

<a id="math.atan"></a>

### math.atan(y, x)

```lua
math.atan( y )
math.atan( y, x )
```

Returns the arc tangent of y/x (in radians), using the signs of both arguments to find the quadrant of the result. It also handles correctly the case of x being zero

The default value for x is 1, so that the call math.atan(y) returns the arc tangent of y

#### Parameters

- **y** (number): numerator for arc tangent
- **x** (number): denominator for arc tangent (defaults to 1)

#### Returns

- **value**: The arc tangent of y/x in radians

<a id="math.ceil"></a>

### math.ceil(value)

```lua
math.ceil( value )
```

This function returns the smallest integer larger than or equal to value. This rounds a number up to the nearest integer. For example, math.ceil(5.2) returns 6.

#### Parameters

- **value** (number): int or float, compute the smallest integer larger than or equal to this number

#### Returns

- **integer**: The smallest integer larger than or equal to value

<a id="math.cos"></a>

### math.cos(value)

```lua
math.cos( value )
```

This function returns the cosine of value (assumed to be in radians).

#### Parameters

- **value** (number): int or float, compute the cosine of this number

#### Returns

- **value**: Cosine of value

<a id="math.cosh"></a>

### math.cosh(value)

```lua
math.cosh( value )
```

This function returns hyperbolic cosine of value.

#### Parameters

- **value** (number): int or float, compute the hyperbolic cosine of this number

#### Returns

- **value**: Hyperbolic cosine of value

<a id="math.deg"></a>

### math.deg(value)

```lua
math.deg( value )
```

This function returns the angle specified by value (given in radians) in degrees.

#### Parameters

- **value** (number): int or float, angle in radians to convert to degrees

#### Returns

- **value**: Angle specified by value (in radians) in degrees

<a id="math.rad"></a>

### math.rad(value)

```lua
math.rad( value )
```

This function returns the angle specified by value (given in degrees) in radians.

#### Parameters

- **value** (number): int or float, angle in degrees to convert to radians

#### Returns

- **value**: Angle specified by value (in degrees) in radians

<a id="math.exp"></a>

### math.exp(value)

```lua
math.exp( value )
```

This function returns **e** raised to value

#### Parameters

- **value** (number): int or float, exponent of e

#### Returns

- **value**: e raised to the power of value

<a id="math.floor"></a>

### math.floor(value)

```lua
math.floor( value )
```

This function returns the largest integer smaller than or equal to value. This rounds a number down to the nearest integer. For example, math.floorTh(5.7) returns 5.

#### Parameters

- **value** (number): int or float, compute the largest integer smaller than or equal to this number

#### Returns

- **integer**: The largest integer smaller than or equal to value

<a id="math.fmod"></a>

### math.fmod(x, y)

```lua
math.fmod( x, y )
```

This function returns the remainder of the division of x by y that rounds the quotient towards zero.

#### Parameters

- **x** (number): int or float
- **y** (number): int or float

#### Returns

- **value**: The remainder of the division of x by y

<a id="math.frexp"></a>

### math.frexp(value)

```lua
math.frexp( value )
```

This function returns m and e such that value = m2^e, e is an integer and the absolute value of m is in the range [0.5, 1) (or zero when x is zero).

#### Parameters

- **value** (number): int or float

#### Returns

- **integer**: m and e such that value = m2^e, e is an integer and the absolute value of m is in the range [0.5, 1) (or zero when x is zero).

<a id="math.ldexp"></a>

### math.ldexp(m, e)

```lua
math.ldexp( m, e )
```

This function returns m2^e (e should be an integer)

#### Parameters

- **m** (number): int or float
- **e** (integer): int

#### Returns

- **value**: m2^e

<a id="math.log"></a>

### math.log(value)

```lua
math.log( value )
```

This function returns the natural logarithm of value

#### Parameters

- **value** (number): int or float, compute the natural logarithm of this value

#### Returns

- **value**: The natural logarithm of value

<a id="math.max"></a>

### math.max(value, ...)

```lua
math.max( value, ... )
```

This function returns maximum value among its arguments.

#### Parameters

- **value** (number): any comparable value
- **...** (number): Additional values accepted by this function; each must match the format or operation.

#### Returns

- **value**: The maximum value among its arguments

<a id="math.min"></a>

### math.min(value, ...)

```lua
math.min( value, ... )
```

This function returns minimum value among its arguments.

#### Parameters

- **value** (number): any comparable value
- **...** (number): Additional values accepted by this function; each must match the format or operation.

#### Returns

- **value**: The minimum value among its arguments

<a id="math.modf"></a>

### math.modf(value)

```lua
math.modf( value )
```

This function returns two numbers, the integral part of value and the fractional part of value.

#### Parameters

- **value** (number): int or float

#### Returns

- **value**: Two numbers, the integral part of value and the fractional part of value

<a id="math.random"></a>

### math.random()

```lua
math.random()
math.random( maximum )
math.random( minimum, maximum )
```

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

#### Returns

- **integer**: A uniform pseudo-random real number or integer (depending on parameters)

<a id="math.randomseed"></a>

### math.randomseed(value)

```lua
math.randomseed( value )
```

Sets value as the “seed” for the pseudo-random number generator. Equal seeds produce equal sequences of numbers.

#### Parameters

- **value** (integer): int, seed of the pseudo-random number generator

#### Returns

- **integer**: A uniform pseudo-random real number or integer (depending on parameters)

<a id="math.sin"></a>

### math.sin(value)

```lua
math.sin( value )
```

This function returns the sine of value (assumed to be in radians).

#### Parameters

- **value** (number): int or float, compute the sine of this number

#### Returns

- **value**: Sine of value

<a id="math.sinh"></a>

### math.sinh(value)

```lua
math.sinh( value )
```

This function returns hyperbolic sine of value.

#### Parameters

- **value** (number): int or float, compute the hyperbolic sine of this number

#### Returns

- **value**: Hyperbolic sine of value

<a id="math.tan"></a>

### math.tan(value)

```lua
math.tan( value )
```

This function returns the tangent of value (assumed to be in radians).

#### Parameters

- **value** (number): int or float, compute the tangent of this number

#### Returns

- **value**: Tangent of value

<a id="math.tanh"></a>

### math.tanh(value)

```lua
math.tanh( value )
```

This function returns hyperbolic tangent of value.

#### Parameters

- **value** (number): int or float, compute the hyperbolic tangent of this number

#### Returns

- **value**: Hyperbolic tangent of value

<a id="math.sqrt"></a>

### math.sqrt(value)

```lua
math.sqrt( value )
```

This function computes the square root of value. You can also use the expression value^0.5 to compute this value.

#### Parameters

- **value** (number): int or float, compute the square root of this number

#### Returns

- **value**: Square root of value

<a id="math.tointeger"></a>

### math.tointeger(value)

```lua
math.tointeger( value )
```

If value is convertible to an integer, returns that integer. Otherwise returns **nil**.

#### Parameters

- **value** (number or string): float, value to convert to integer

#### Returns

- **integer**: value converted to an integer, or nil

<a id="math.type"></a>

### math.type(value)

```lua
math.type( value )
```

This function returns “integer” if value is an integer, “float” if it is a float, or **nil** if value is not a number.

#### Parameters

- **value** (any): int or float, get the type of this value

#### Returns

- **integer**: “integer” or “float”

<a id="math.ult"></a>

### math.ult(m, n)

```lua
math.ult( m, n )
```

This function returns a boolean, true if integer m is below integer n when they are compared as unsigned integers.

#### Parameters

- **m** (integer): value for m
- **n** (integer): value for n

#### Returns

- **boolean**: true if m is below integer n when compared as unsigned

<a id="entry.math.huge"></a>

### math.huge

```lua
math.huge
```

A value larger than or equal to any other numerical value.

<a id="entry.math.pi"></a>

### math.pi

```lua
math.pi
```

The value of **pi**.

<a id="entry.math.maxinteger"></a>

### math.maxinteger

```lua
math.maxinteger
```

Specifies an integer with the maximum value for an integer

<a id="entry.math.mininteger"></a>

### math.mininteger

```lua
math.mininteger
```

Specifies an integer with the minimum value for an integer

<a id="section-Date-and-Time"></a>

## Date and Time

<a id="os.clock"></a>

### os.clock()

```lua
os.clock()
```

Returns an approximation of the amount in seconds of CPU time used by the program.

#### Returns

- **number**: Approximation of the amount in seconds of CPU time used by the program.

<a id="os.difftime"></a>

### os.difftime(t2, t1)

```lua
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.

#### Parameters

- **t2** (integer): Ending time
- **t1** (integer): Starting time

#### Returns

- **number**: Number of seconds from time t1 to time t2.

<a id="os.date"></a>

### os.date(format)

```lua
os.date()
os.date( format )
os.date( format, time )
```

Returns a string or a table containing the 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 fields: 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 flag, 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.

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

#### Parameters

- **format** (string): String used to format the returned date

#### Returns

- **string**: A string or a table containing the date and time.

<a id="os.setlocale"></a>

### os.setlocale(locale)

```lua
os.setlocale( locale )
os.setlocale( locale, category )
```

Sets the current locale of the program. locale is a string specifying a locale; category is an optional string describing which category to change: “all”, “collate”, “ctype”, “monetary”, “numeric”, or “time”; the default category is “all”. The function returns the name of the new locale, or nil if the request cannot be honored.

If locale is the empty string, the current locale is set to an implementation-defined native locale. If locale is the string “C”, the current locale is set to the standard C locale.

When called with nil as the first argument, this function only returns the name of the current locale for the given category.

#### Parameters

- **locale** (string): String specifying a locale, can be nil or the empty string.

#### Returns

- **value**: When called with nil for the first argument, returns the name of the current locale for the given category.

<a id="os.time"></a>

### os.time()

```lua
os.time()
os.time( table )
```

Returns the current time when called without arguments, or a time representing the date and time specified by the given table. This table must have fields year, month, and day, and may have fields hour, min, sec, and isdst (for a description of these fields, 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 specified, and the number returned by time can be used only as an argument to date and difftime.

#### Returns

- **number**: 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 specified, and the number returned by time can be used only as an argument to date and difftime.

<a id="section-Text-Files"></a>

## Text Files

<a id="string"></a>

### string

Read a text file with `string.read()` or save text with `string.save()`. Use an asset key to choose the file.

**Reading and saving text files**

```lua
 function setup()
     local contentsOrNil = string.read(asset.."Hello.txt")
     print("Contents: " .. tostring(contentsOrNil))
     if test == "World" then
         string.save(asset.."Hello.txt", "Hello")
     else
         string.save(asset.."Hello.txt", "World")
     end
 end
```

<a id="string.read"></a>

### string.read(assetKey)

```lua
string.read(assetKey)
```

Reads the contents of a file as text.

read the file contents

#### Parameters

- **assetKey** (assetKey): The asset key of the file.

#### Returns

- **string**: The contents of the file.

<a id="string.save"></a>

### string.save(assetKey, text, callback)

```lua
string.save(assetKey, text, callback)
```

Saves text to a file.

If a callback is supplied, saving will happen in the background. Multiple calls to save the same file are grouped and only the latest save will be performed.

save the text to a file

#### Parameters

- **assetKey** (assetKey): The asset key of the file.
- **text** (string): The text to save.
- **callback** (function, optional): Optional completion callback function(ok, err).

#### Example

```lua
string.save(asset.documents .. "Config.json", json.encode(config), function(ok, err)
    if not ok then
        print("Save failed:", err)
    end
end)
```

<a id="section-Importing-Code"></a>

## Importing Code

<a id="Importing-Lua-Code"></a>

### Importing Lua Code

Use `require()` with an asset key to reuse Lua code from another file or project.

<a id="Importing-a-Codea-Project"></a>

### Importing a Codea Project

For Codea project asset keys, all Lua files except Main.lua are imported by default, including the global variables and functions.

`require.option.loadMain` can be used to import Main.lua.
`require.option.noImport` can be used to prevent importing global variables and functions.

<a id="Importing-a-Lua-File"></a>

### Importing a Lua File

For single Lua file asset keys, only the specified file is imported, including its global variables and functions by default.

`require.option.noImport` can be used to prevent importing global variables and functions.

<a id="section-Import-Functions"></a>

## Import Functions

<a id="require"></a>

### require(assetKey, ...)

```lua
require(assetKey, ...)
```

Import a single file from the specified asset key.

import a Lua file from an asset key

#### Parameters

- **assetKey** (assetKey): The asset key of the file to import
- **...** (integer): Optional require.option values, such as loadMain or noImport.

#### Returns

- **any**: Value returned by the imported file, if any

#### Example

```lua
require(asset.documents.MyLibrary, require.option.noImport, require.option.loadMain)

myFeature = require(asset.documents.MyOtherLibrary.MyFeature, require.option.noImport)

require(asset.documents.MyOtherLibrary.MyOtherFeature)
```

<a id="require-2"></a>

### require

```lua
require
```

an option value for require

<a id="require.option"></a>

### require.option

```lua
require.option
```

an option value for require

<a id="section-Pasteboard"></a>

## Pasteboard

<a id="pasteboard"></a>

### pasteboard

Copy and paste strings, images, colors and URLs.

Check `hasStrings`, `hasImages`, `hasColors` or `hasURLs` before reading
the corresponding values. Reading data copied from another app may show a
system notification; checking whether it is available does not.

```lua
pasteboard.string = "Copied from Codea"
if pasteboard.hasStrings then
    print(pasteboard.string)
end
```

Use `pasteboard.string` for both copying and reading text.

<a id="pasteboard.name"></a>

### pasteboard.name

```lua
pasteboard.name
```

The name of the pasteboard.

get the name of this pasteboard

<a id="pasteboard.numberOfItems"></a>

### pasteboard.numberOfItems

```lua
pasteboard.numberOfItems
```

The number of items in the pasteboard.

get the number of items on this pasteboard

<a id="pasteboard.hasStrings"></a>

### pasteboard.hasStrings

```lua
pasteboard.hasStrings
```

Whether the pasteboard contains one or more strings.

get whether this pasteboard has strings

<a id="pasteboard.string"></a>

### pasteboard.string

```lua
pasteboard.string
```

get or set the string on this pasteboard

<a id="pasteboard.strings"></a>

### pasteboard.strings

```lua
pasteboard.strings
```

get or set the strings on this pasteboard

<a id="pasteboard.hasImages"></a>

### pasteboard.hasImages

```lua
pasteboard.hasImages
```

get whether this pasteboard has images

<a id="pasteboard.image"></a>

### pasteboard.image

```lua
pasteboard.image
```

get or set the image on this pasteboard

<a id="pasteboard.images"></a>

### pasteboard.images

```lua
pasteboard.images
```

get or set the images on this pasteboard

<a id="pasteboard.hasColors"></a>

### pasteboard.hasColors

```lua
pasteboard.hasColors
```

get whether this pasteboard has colors

<a id="pasteboard.color"></a>

### pasteboard.color

```lua
pasteboard.color
```

get or set the color on this pasteboard

<a id="pasteboard.colors"></a>

### pasteboard.colors

```lua
pasteboard.colors
```

get or set the colors on this pasteboard

<a id="pasteboard.hasURLs"></a>

### pasteboard.hasURLs

```lua
pasteboard.hasURLs
```

get whether this pasteboard has URLs

<a id="pasteboard.URL"></a>

### pasteboard.URL

```lua
pasteboard.URL
```

get or set the URL on this pasteboard

<a id="pasteboard.URLs"></a>

### pasteboard.URLs

```lua
pasteboard.URLs
```

get or set the URLs on this pasteboard

<a id="section-Legacy-Compatibility"></a>

## Legacy Compatibility

<a id="Using-Legacy-Compatibility"></a>

### Using Legacy Compatibility

Codea supplies compatibility globals from `codea/legacy.lua`
so older projects can migrate gradually. These are migration helpers, not the
preferred API for new code. The wrappers do not reproduce all behavior of older Codea versions.
Use the corresponding modules below when updating a project.

<a id="Migrating-a-project"></a>

### Migrating a project

Replace drawing-state globals with `style` and transforms with `matrix`.
Use `image.read` and `image.save` for assets, `storage` for persistent data,
and `time` and `touch` for current frame state. Keep paired push/pop calls
balanced. Test text alignment and image filtering: the compatibility layer
translates old conventions rather than simply renaming every call.

The old `physics` global is a compatibility facade over `physics2d`. It
translates numeric body/joint constants and legacy collision callbacks; new
projects should use the world, body, collider and joint APIs directly.
`CAMERA` and `CAMERA_DEPTH` follow sensor images (or a placeholder until a
frame arrives). `cameraSource` reads or changes the sensor camera selection.

<a id="section-Aliases"></a>

## Aliases

<a id="pushStyle"></a>

### pushStyle()

**Deprecated.** Deprecated since version 4.0: Use style.push().

```lua
pushStyle()
```

Compatibility wrapper for `style.push()`.

legacy alias; use style.push()

<a id="popStyle"></a>

### popStyle()

**Deprecated.** Deprecated since version 4.0: Use style.pop().

```lua
popStyle()
```

Compatibility wrapper for `style.pop()`.

legacy alias; use style.pop()

<a id="resetStyle"></a>

### resetStyle()

**Deprecated.** Deprecated since version 4.0: Use style.reset().

```lua
resetStyle()
```

Compatibility wrapper for `style.reset()`.

legacy alias; use style.reset()

<a id="blendMode"></a>

### blendMode(...)

**Deprecated.** Deprecated since version 4.0: Use style.blend(...).

```lua
blendMode(...)
```

Compatibility wrapper for `style.blend(...)`.

legacy alias; use style.blend(...)

#### Parameters

- **...** (any): Arguments accepted by style.blend(...); see that API for types and defaults.

<a id="noTint"></a>

### noTint()

**Deprecated.** Deprecated since version 4.0: Use style.tint(255, 255, 255, 255).

```lua
noTint()
```

Compatibility wrapper for `style.tint(255, 255, 255, 255)`.

legacy alias; use style.tint(255, 255, 255, 255)

<a id="spriteMode"></a>

### spriteMode(...)

**Deprecated.** Deprecated since version 4.0: Use style.spriteMode(...).

```lua
spriteMode(...)
```

Compatibility wrapper for `style.spriteMode(...)`.

legacy alias; use style.spriteMode(...)

#### Parameters

- **...** (any): Arguments accepted by style.spriteMode(...); see that API for types and defaults.

<a id="spriteSize"></a>

### spriteSize(...)

**Deprecated.** Deprecated since version 4.0: Use image.read(assetKey).width and .height.

```lua
spriteSize(...)
```

Compatibility wrapper for `image.read(assetKey).width and .height`.

legacy alias; use image.read(assetKey).width and .height

#### Parameters

- **...** (any): Arguments accepted by image.read(assetKey).width and .height; see that API for types and defaults.

<a id="rectMode"></a>

### rectMode(...)

**Deprecated.** Deprecated since version 4.0: Use style.rectMode(...).

```lua
rectMode(...)
```

Compatibility wrapper for `style.rectMode(...)`.

legacy alias; use style.rectMode(...)

#### Parameters

- **...** (any): Arguments accepted by style.rectMode(...); see that API for types and defaults.

<a id="ellipseMode"></a>

### ellipseMode(...)

**Deprecated.** Deprecated since version 4.0: Use style.ellipseMode(...).

```lua
ellipseMode(...)
```

Compatibility wrapper for `style.ellipseMode(...)`.

legacy alias; use style.ellipseMode(...)

#### Parameters

- **...** (any): Arguments accepted by style.ellipseMode(...); see that API for types and defaults.

<a id="lineCapMode"></a>

### lineCapMode(...)

**Deprecated.** Deprecated since version 4.0: Use style.lineCap(...).

```lua
lineCapMode(...)
```

Compatibility wrapper for `style.lineCap(...)`.

legacy alias; use style.lineCap(...)

#### Parameters

- **...** (any): Arguments accepted by style.lineCap(...); see that API for types and defaults.

<a id="noSmooth"></a>

### noSmooth(...)

**Deprecated.** Deprecated since version 4.0: Use style.noSmooth() and style.filter(image.filter.point).

```lua
noSmooth(...)
```

Compatibility wrapper for `style.noSmooth() and style.filter(image.filter.point)`.

legacy alias; use style.noSmooth() and style.filter(image.filter.point)

#### Parameters

- **...** (any): Arguments accepted by style.noSmooth() and style.filter(image.filter.point); see that API for types and defaults.

<a id="smooth"></a>

### smooth(...)

**Deprecated.** Deprecated since version 4.0: Use style.smooth() and style.filter(image.filter.linear).

```lua
smooth(...)
```

Compatibility wrapper for `style.smooth() and style.filter(image.filter.linear)`.

legacy alias; use style.smooth() and style.filter(image.filter.linear)

#### Parameters

- **...** (any): Arguments accepted by style.smooth() and style.filter(image.filter.linear); see that API for types and defaults.

<a id="pushMatrix"></a>

### pushMatrix()

**Deprecated.** Deprecated since version 4.0: Use matrix.push().

```lua
pushMatrix()
```

Compatibility wrapper for `matrix.push()`.

legacy alias; use matrix.push()

<a id="popMatrix"></a>

### popMatrix()

**Deprecated.** Deprecated since version 4.0: Use matrix.pop().

```lua
popMatrix()
```

Compatibility wrapper for `matrix.pop()`.

legacy alias; use matrix.pop()

<a id="resetMatrix"></a>

### resetMatrix()

**Deprecated.** Deprecated since version 4.0: Use matrix.reset().

```lua
resetMatrix()
```

Compatibility wrapper for `matrix.reset()`.

legacy alias; use matrix.reset()

<a id="modelMatrix"></a>

### modelMatrix(...)

**Deprecated.** Deprecated since version 4.0: Use matrix.model(...).

```lua
modelMatrix(...)
```

Compatibility wrapper for `matrix.model(...)`.

legacy alias; use matrix.model(...)

#### Parameters

- **...** (any): Arguments accepted by matrix.model(...); see that API for types and defaults.

<a id="fontMetrics"></a>

### fontMetrics(...)

**Deprecated.** Deprecated since version 4.0: Use font.metrics(...).

```lua
fontMetrics(...)
```

Compatibility wrapper for `font.metrics(...)`.

legacy alias; use font.metrics(...)

#### Parameters

- **...** (any): Arguments accepted by font.metrics(...); see that API for types and defaults.

<a id="readImage"></a>

### readImage(...)

**Deprecated.** Deprecated since version 4.0: Use image.read(...).

```lua
readImage(...)
```

Compatibility wrapper for `image.read(...)`.

legacy alias; use image.read(...)

#### Parameters

- **...** (any): Arguments accepted by image.read(...); see that API for types and defaults.

<a id="saveImage"></a>

### saveImage(...)

**Deprecated.** Deprecated since version 4.0: Use image.save(...).

```lua
saveImage(...)
```

Compatibility wrapper for `image.save(...)`.

legacy alias; use image.save(...)

#### Parameters

- **...** (any): Arguments accepted by image.save(...); see that API for types and defaults.

<a id="triangulate"></a>

### triangulate(...)

**Deprecated.** Deprecated since version 4.0: Use mesh.triangulate(...).

```lua
triangulate(...)
```

Compatibility wrapper for `mesh.triangulate(...)`.

legacy alias; use mesh.triangulate(...)

#### Parameters

- **...** (any): Arguments accepted by mesh.triangulate(...); see that API for types and defaults.

<a id="setContext"></a>

### setContext(...)

**Deprecated.** Deprecated since version 4.0: Use context.push(image) and context.pop().

```lua
setContext(...)
```

Compatibility wrapper for `context.push(image) and context.pop()`.

legacy alias; use context.push(image) and context.pop()

#### Parameters

- **...** (any): Arguments accepted by context.push(image) and context.pop(); see that API for types and defaults.

<a id="soundBufferSize"></a>

### soundBufferSize(...)

**Deprecated.** Deprecated since version 4.0: Use the sound module; there is no buffer-size equivalent.

```lua
soundBufferSize(...)
```

Unsupported compatibility stub. Returns `0, 0`; it does not configure audio.

unsupported legacy audio buffer stub

#### Parameters

- **...** (any): Compatibility arguments; this stub does not use them.

#### Returns

- **number**: 
- **number**: 

<a id="readLocalData"></a>

### readLocalData(key, defaultValue)

**Deprecated.** Deprecated since version 4.0: Use storage.global:namespace("__legacy.local." .. asset.name):get(tostring(key), defaultValue).

```lua
readLocalData(key, defaultValue)
```

Compatibility storage operation using `storage.global:namespace("__legacy.local." .. asset.name):get(tostring(key), defaultValue)`.
Saving `nil` deletes a key. Local data uses a namespace based on the project name.

legacy local storage read

#### Parameters

- **key** (string): Name of the stored value.
- **defaultValue** (any): Value returned when the key has not been saved.

<a id="saveLocalData"></a>

### saveLocalData(key, value)

**Deprecated.** Deprecated since version 4.0: Use storage.global:namespace("__legacy.local." .. asset.name):set(tostring(key), value).

```lua
saveLocalData(key, value)
```

Compatibility storage operation using `storage.global:namespace("__legacy.local." .. asset.name):set(tostring(key), value)`.
Saving `nil` deletes a key. Local data uses a namespace based on the project name.

legacy local storage save

#### Parameters

- **key** (string): Name of the stored value.
- **value** (any): Value to save; nil removes the key. Use a serializable value supported by storage.

<a id="listLocalData"></a>

### listLocalData()

**Deprecated.** Deprecated since version 4.0: Use storage.global:namespace("__legacy.local." .. asset.name):keys().

```lua
listLocalData()
```

Compatibility storage operation using `storage.global:namespace("__legacy.local." .. asset.name):keys()`.
Saving `nil` deletes a key. Local data uses a namespace based on the project name.

legacy local storage list

<a id="clearLocalData"></a>

### clearLocalData()

**Deprecated.** Deprecated since version 4.0: Use storage.global:namespace("__legacy.local." .. asset.name):clear().

```lua
clearLocalData()
```

Compatibility storage operation using `storage.global:namespace("__legacy.local." .. asset.name):clear()`.
Saving `nil` deletes a key. Local data uses a namespace based on the project name.

legacy local storage clear

<a id="readProjectData"></a>

### readProjectData(key, defaultValue)

**Deprecated.** Deprecated since version 4.0: Use storage.project:get("__legacy.project." .. tostring(key), defaultValue).

```lua
readProjectData(key, defaultValue)
```

Compatibility storage operation using `storage.project:get("__legacy.project." .. tostring(key), defaultValue)`.
Saving `nil` deletes a key. Local data uses a namespace based on the project name.

legacy project storage read

#### Parameters

- **key** (string): Name of the stored value.
- **defaultValue** (any): Value returned when the key has not been saved.

<a id="saveProjectData"></a>

### saveProjectData(key, value)

**Deprecated.** Deprecated since version 4.0: Use storage.project:set("__legacy.project." .. tostring(key), value).

```lua
saveProjectData(key, value)
```

Compatibility storage operation using `storage.project:set("__legacy.project." .. tostring(key), value)`.
Saving `nil` deletes a key. Local data uses a namespace based on the project name.

legacy project storage save

#### Parameters

- **key** (string): Name of the stored value.
- **value** (any): Value to save; nil removes the key. Use a serializable value supported by storage.

<a id="listProjectData"></a>

### listProjectData()

**Deprecated.** Deprecated since version 4.0: Use storage.project:keys() and filter the legacy prefix when migrating existing data.

```lua
listProjectData()
```

Returns sorted keys from `storage.project` beginning with `__legacy.project.`,
with that prefix removed. Other storage keys are excluded.

list legacy project storage keys

<a id="clearProjectData"></a>

### clearProjectData()

**Deprecated.** Deprecated since version 4.0: Use storage.project:set(key, nil) for each legacy-prefixed key. Clearing
the entire store would also delete unrelated data.

```lua
clearProjectData()
```

Deletes only `storage.project` keys beginning with `__legacy.project.`.
Other project data is retained.

delete legacy project storage keys

<a id="readGlobalData"></a>

### readGlobalData(key, defaultValue)

**Deprecated.** Deprecated since version 4.0: Use storage.global:get("__legacy.global." .. tostring(key), defaultValue).

```lua
readGlobalData(key, defaultValue)
```

Compatibility storage operation using `storage.global:get("__legacy.global." .. tostring(key), defaultValue)`.
Saving `nil` deletes a key. Local data uses a namespace based on the project name.

legacy global storage read

#### Parameters

- **key** (string): Name of the stored value.
- **defaultValue** (any): Value returned when the key has not been saved.

<a id="saveGlobalData"></a>

### saveGlobalData(key, value)

**Deprecated.** Deprecated since version 4.0: Use storage.global:set("__legacy.global." .. tostring(key), value).

```lua
saveGlobalData(key, value)
```

Compatibility storage operation using `storage.global:set("__legacy.global." .. tostring(key), value)`.
Saving `nil` deletes a key. Local data uses a namespace based on the project name.

legacy global storage save

#### Parameters

- **key** (string): Name of the stored value.
- **value** (any): Value to save; nil removes the key. Use a serializable value supported by storage.

<a id="listGlobalData"></a>

### listGlobalData()

**Deprecated.** Deprecated since version 4.0: Use storage.global:keys() and filter the legacy prefix when migrating existing data.

```lua
listGlobalData()
```

Returns sorted keys from `storage.global` beginning with `__legacy.global.`,
with that prefix removed. Other storage keys are excluded.

list legacy global storage keys

<a id="entry.DeltaTime"></a>

### DeltaTime

**Deprecated.** Deprecated since version 4.0: Use time.delta (or time.fixedDelta in fixedUpdate).

```lua
DeltaTime
```

Legacy compatibility value.

legacy value; use time.delta (or time.fixedDelta in fixedUpdate)

<a id="entry.ElapsedTime"></a>

### ElapsedTime

**Deprecated.** Deprecated since version 4.0: Use time.elapsed.

```lua
ElapsedTime
```

Legacy compatibility value.

legacy value; use time.elapsed

<a id="entry.CurrentTouch"></a>

### CurrentTouch

**Deprecated.** Deprecated since version 4.0: Use touch.current.

```lua
CurrentTouch
```

Legacy compatibility value.

legacy value; use touch.current

<a id="entry.CAMERA"></a>

### CAMERA

**Deprecated.** Deprecated since version 4.0: Use sensor.cameraColor.

```lua
CAMERA
```

Legacy compatibility value.

legacy value; use sensor.cameraColor

<a id="entry.CAMERA_DEPTH"></a>

### CAMERA_DEPTH

**Deprecated.** Deprecated since version 4.0: Use sensor.cameraDepth.

```lua
CAMERA_DEPTH
```

Legacy compatibility value.

legacy value; use sensor.cameraDepth

<a id="entry.physics"></a>

### physics

**Deprecated.** Deprecated since version 4.0: Use physics2d.

```lua
physics
```

Legacy compatibility value.

legacy value; use physics2d

<a id="cameraSource"></a>

### cameraSource(source)

**Deprecated.** Deprecated since version 4.0: Read or assign sensor.cameraSource directly.

```lua
cameraSource(source)
```

With no argument, returns `sensor.cameraSource`. With an argument, sets
`sensor.cameraSource` and ensures the legacy camera image placeholder exists.

legacy sensor camera selection

#### Parameters

- **source** (integer, optional): Camera source identifier, such as CAMERA_BACK or CAMERA_FRONT.

<a id="section-Output"></a>

## Output

<a id="output"></a>

### output

Use `print(...)` to inspect values while a project runs. Clear old messages
when starting a new calculation or test; do not clear on every frame or you
will lose useful diagnostics.

```lua
output.clear()
print("Starting a new run")
```

<a id="output.clear"></a>

### output.clear()

```lua
output.clear()
```

Clears messages from the viewer’s output pane. It does not change project
variables or restart the project.

clear the output pane
