Wiki

Clone wiki

Core / Documentation

===Graphics===
====Drawing Shapes, Styles and Positioning====

----
=====How Codea Draws=====
======Description======


When you begin a new project in Codea you'll notice that it consists of a tab called **Main** and some template code. Your project can consist of several tabs, the initial one is always called **Main**. If you add more files they will be listed across the top.

\\

{{{
#!lua
function setup()
    print("Hello World!")
end

function draw()
    background(0,0,0)

    -- Do your drawing here
end
}}}


\\
This is the framework that your project will use to run. There are two functions defined for you initially: **setup()** and **draw()**.

\\
**setup()** and **draw()** are executed by Codea when you press the play button to run your project. The **setup()** function is called once, at the start, and then the **draw()** function is called repeatedly (60 times per second, to be exact). In **setup()** Codea expects you to set up your initial program state, and in **draw()** you can tell Codea to render graphics onto the screen, update your program state over time, and so on.

\\
In the next two sections we will cover these functions in detail.



======Related======

# [[Documentation#drawoverview|drawOverview]]
# [[Documentation#setupoverview|setupOverview]]

----
=====The draw() function=====
======Description======


When you press the play button, the **draw()** function is repeatedly executed by Codea. Codea tries to execute the **draw()** function 60 times per second - if it can. Codea can't guarantee that your **draw()** function will be called 60 times per second (it may slow down if your project performs a lot of computation, or creates highly complex drawing).

\\

{{{
#!lua
function draw()
    -- Set the background color to blue-ish
    background(100,120,180)

    -- Set the fill color to red
    fill(255,0,0)

    -- Set a wide outline
    strokeWidth(5)

    -- Set the outline color to white
    stroke(255)

    -- Draw a red circle with a white outline
    -- In the center of the screen
    ellipse( WIDTH/2, HEIGHT/2, 200 )
end
}}}


\\
Note that the above code will run 60 times every second. That is, you are telling Codea to paint the background blue and draw a red circle with a white outline 60 times per second, from scratch. It does this so that you can create smooth motion by changing your program state over time, and updating your drawing code to reflect the new state. For example, you might make the circle bounce on the ground by changing its Y-position (the second parameter to **ellipse()**) every frame.



======Related======

# [[Documentation#setupoverview|setupOverview]]

----
=====The setup() function=====
======Description======


When you press the play button Codea will call the **setup()** function once, before it begins calling the **draw()** function. In here you can perform any once-off computations, set up program state, set the display mode, and do things that you don't need to do every frame. For example, the **setup()** function below creates a global variable controlled by a slider. This variable is then used in the **draw()** function to control the Y-position of a circle.

\\

{{{
#!lua
function setup()
    displayMode(STANDARD)
    parameter("YPosition", 0, HEIGHT, HEIGHT/2)
end

function draw()
    background(0)
    fill(255,0,0)
    ellipse( WIDTH/2, YPosition, 200 )
end
}}}




======Related======

# [[Documentation#drawoverview|drawOverview]]

----
=====clip( x, y, width, height )=====
======Description======


Constrains all drawing performed after this function call to the rectangle specified by **x**, **y**, **width**, **height**. Any drawing that occurs outside the bounds will not be visible.

\\
This can be used to make split-screen multiplayer games, for example. When called with zero arguments **clip()** disables the clipping rectangle, allowing drawing to occur anywhere on the screen.



======Syntax======

{{{
#!lua
clip( x, y, width, height )
clip() --Disables clipping
}}}

======Parameters======

|=Name|=Description|
|x|integer, x coordinate of the lower-left corner of the clipping rectangle|
|y|integer, y coordinate of the lower-left corner of the clipping rectangle|
|width|integer, width of the clipping rectangle|
|height|integer, height of the clipping rectangle|


----
=====setContext( image )=====
======Examples======

{{{
#!lua
-- Creates an image of an ellipse and rect
function createImage()
    myImage = image(400,400)

    setContext( myImage )
    ellipse(200, 200, 200)
    rect(0, 0, 100, 100)
    setContext()

    return myImage
end
}}}

======Description======


This call causes all drawing operations to take place on the specified image instead of on-screen. Drawing commands such as **ellipse**, **sprite** and **rect** will render into the image given as an argument to **setContext()**.

\\
Calling **setContext()** with no arguments causes all drawing operations to return to their regular on-screen drawing functionality. Because Codea uses pre-multiplied drawing, any image passed to **setContext()** will have its premultiplied flag set to true.



======Syntax======

{{{
#!lua
setContext()
setContext( image )
}}}

======Parameters======

|=Name|=Description|
|image|image, all drawing operations will occur on this image instead of on screen|

======Related======

# [[Documentation#image|image]]

----
=====noise( x, y, z )=====
======Description======


Returns a Perlin noise value in the range -1.0 to 1.0 sampled at location **x**, **y**, **z**. Any parameters not provided to this function are treated as zero.

======Syntax======

{{{
#!lua
noise( x )
noise( x, y )
noise( x, y, z )
}}}

======Parameters======

|=Name|=Description|
|x|float, x location of the sample|
|y|float, y location of the sample|
|z|float, z location of the sample|

======Returns======


Perlin noise value from -1.0 to 1.0 at the given location.


----
=====backingMode( mode )=====
======Description======


Sets the backing mode to retained or standard. Retained backing will keep the results of the previous frame and is useful if no background function is called in draw. **Using retained backing will impact your framerate.**

======Syntax======

{{{
#!lua
backingMode( STANDARD | RETAINED )
}}}

======Parameters======

|=Name|=Description|
|mode|Optional: either STANDARD or RETAINED|

======Returns======


The current backing mode if no mode parameter given, otherwise nothing

======Related======

# [[Documentation#background|background]]

----
=====background( red, green, blue )=====
======Examples======

{{{
#!lua
function draw()
    -- Dark blueish background
    background(0, 50, 70)

    -- Do some drawing
end
}}}

======Description======


Clears the background to the specified color. You should generally call this at the start of your **draw()** function in order to clear the contents of the previous frame.

======Syntax======

{{{
#!lua
background( gray )
background( gray, alpha )
background( red, green, blue )
background( red, green, blue, alpha )
background( color )
}}}

======Parameters======

|=Name|=Description|
|gray|int from 0 to 255, specifies value between white and black|
|alpha|int from 0 to 255, specifies opacity of the background|
|red|int from 0 to 255, specifies red amount of the background|
|green|int from 0 to 255, specifies green amount of the background|
|blue|int from 0 to 255, specifies blue amount of the background|
|color|a value of the color datatype|

======Related======

# [[Documentation#color|color]]
# [[Documentation#backingmode|backingMode]]

----
=====ellipse( x, y, width, height )=====
======Description======


Draws an ellipse centered at **x, y** with horizontal and vertical dimensions specified by **width** and **height**. The **ellipseMode()** function sets how these parameters are interpreted. Use **fill()** to set the color of an ellipse and **stroke()** to set its outline color.

======Syntax======

{{{
#!lua
ellipse( x, y, diameter )
ellipse( x, y, width, height )
}}}

======Parameters======

|=Name|=Description|
|x|x-coordinate of the ellipse|
|y|y-coordinate of the ellipse|
|width|width of the ellipse|
|height|height of the ellipse|

======Related======

# [[Documentation#ellipsemode|ellipseMode]]
# [[Documentation#fill|fill]]
# [[Documentation#stroke|stroke]]

----
=====rect( x, y, width, height )=====
======Description======


Draws a rectangle with its lower-left corner positioned at **x, y** and sized at **width, height**. Use **fill()** to set the color of a rectangle and **stroke()** to set the outline color. The interpretation of a rectangle's **x, y, width** and **height** parameters can be specified using the **rectMode()** function. **rectMode()** is set to **CORNER** by default.

======Syntax======

{{{
#!lua
rect( x, y, width, height )
}}}

======Parameters======

|=Name|=Description|
|x|x-coordinate of the lower-left corner|
|y|y-coordinate of the lower-left corner|
|width|width of the rectangle|
|height|height of the rectangle|

======Related======

# [[Documentation#rectmode|rectMode]]
# [[Documentation#fill|fill]]
# [[Documentation#stroke|stroke]]

----
=====sprite( name, x, y )=====
======Examples======

{{{
#!lua
background(127, 127, 127, 255)
sprite("Planet Cute:Character Boy",
	WIDTH / 2, HEIGHT / 2)
}}}


{{{
#!lua
background(127, 127, 127, 255)
tint(255, 0, 0)
sprite("Planet Cute:Character Boy",
	WIDTH / 2, HEIGHT / 2)
}}}

======Description======


Draws a sprite. A sprite is a a bitmap graphic such as a character or space ship. The name of the sprite specifies the sprite pack and sprite to use. Alternatively, an image can be passed in instead of a name to draw that image instead.

\\
By default the x and y parameters set the location of the center of the sprite, the origin mode can be set using the **spriteMode()** function. The last two parameters are optional and set the width and height in pixels, if these are not specified the sprite will be rendered at the pixel dimensions of its graphic. Sprites can be tinted with the **tint()** function.



======Syntax======

{{{
#!lua
sprite( name, x, y )
sprite( name, x, y, width )
sprite( name, x, y, width, height )

sprite( image, x, y )
sprite( image, x, y, width )
sprite( image, x, y, width, height )
}}}

======Parameters======

|=Name|=Description|
|name|name of the sprite to use, in the following format:\\

{{{
#!lua
"SpritePack:SpriteName"
}}}
|
|image|image to draw onto the screen|
|x|x-coordinate of the center of the sprite (this can be changed with **spriteMode**)|
|y|y-coordinate of the center of the sprite (this can be changed with **spriteMode**)|
|width|optional width of the sprite in pixels|
|height|optional width of the sprite in pixels. If **width** is specified and **height** is not, then **height** is automatically computed to preserve the aspect ratio of the image.|

======Related======

# [[Documentation#spritemode|spriteMode]]
# [[Documentation#tint|tint]]
# [[Documentation#notint|noTint]]
# [[Documentation#image|image]]

----
=====text( string, x, y )=====
======Examples======

{{{
#!lua
background(100, 120, 160)
font("Georgia")
fill(255)
fontSize(20)
textWrapWidth(70)
text("Hello World!", WIDTH/2, HEIGHT/2)
}}}

======Description======


Draws text at the given **x**, **y** location. You can set the font used by **text()** with the **font()** function. Text appearance can be further configured by using the **fontSize()** and **fill()** functions.

\\
You can change the alignment and wrapping of text by using **textAlign()** and **textWrapWidth()**. If **textWrapWidth()** is set to 0 (the default) text will be drawn on one line. If **textWrapWidth()** is set to a value greater than 0 the text will word-wrap if it exceeds the width specified by **textWrapWidth()**

\\
By default the x and y parameters set the location of the center of the text, the origin mode can be set using the **textMode()** function. Text color can be changed with the **fill()** function.

\\
If you need to get the dimensions of a string in the current style, see the **textSize** function documentation.



======Syntax======

{{{
#!lua
text( string, x, y )
}}}

======Parameters======

|=Name|=Description|
|string|the text string that you would like to draw onto the screen|
|x|x-coordinate of the center of the text (this can be changed with **textMode**)|
|y|y-coordinate of the center of the text (this can be changed with **textMode**)|

======Related======

# [[Documentation#font|font]]
# [[Documentation#fill|fill]]
# [[Documentation#fontsize|fontSize]]
# [[Documentation#textmode|textMode]]
# [[Documentation#textalign|textAlign]]
# [[Documentation#textwrapwidth|textWrapWidth]]
# [[Documentation#textsize|textSize]]

----
=====line( x1, y1, x2, y2 )=====
======Examples======

{{{
#!lua
function draw()
    background(128)
    stroke(255)
    line(10, 10, 80, 80)
end
}}}

======Description======


Draws a line between the two points specified by **x1,y1** and **x2,y2**. A line's color can be set with the **stroke()** function and its width can be set with the **strokeWidth()** function. A line's cap style can be changed with the **lineCapMode()** function. Note that line cap modes only take effect when drawing with the rendering mode set to **smooth()**. When using **noSmooth()**, lines will be rendered using square end caps.

======Syntax======

{{{
#!lua
line( x1, y1, x2, y2 )
}}}

======Parameters======

|=Name|=Description|
|x1|x-coordinate of the first point|
|y1|y-coordinate of the first point|
|x2|x-coordinate of the second point|
|y2|y-coordinate of the second point|

======Returns======


None

======Related======

# [[Documentation#linecapmode|lineCapMode]]
# [[Documentation#stroke|stroke]]
# [[Documentation#strokewidth|strokeWidth]]
# [[Documentation#smooth|smooth]]
# [[Documentation#nosmooth|noSmooth]]

----
=====image=====
======Examples======

{{{
#!lua
-- Create a 400x400 pixel image
myImage = image(400, 400)

-- Set a pixel
myImage:set(10,10,128,128,128,255)

-- Get a pixel
r,g,b,a = myImage:get(10,10)
}}}

======Description======


This type represents a 2D raster image, pixels can be set with image:set(x, y, color) and read with image:get(x, y). Images and sub-rectangles can be copied with image:copy(). Draw images onto the screen using sprite(image,x,y). See the relevant documentation pages for more details.You can access the width or the height of an image through its width and height properties.

\\
The **image.premultiplied** flag allows you to specify whether the image was created with premultiplied alpha. Generally, for images you create yourself using **image:set()**, you'll want this set to **false** (the default). For images used with **setContext()** you will want this set to **true**. Note that using an image with **setContext()** will automatically set its premultiplied flag to **true**.

The constructor can alternatively take png or jpeg encoded binary data which it will decode and use to construct the image. Using this will enable premultiplied alpha, and the encoded data is assumed to be premultiplied.



======Syntax======

{{{
#!lua
image( width, height )
image.width
image.height
image(data)
}}}

======Parameters======

|=Name|=Description|
|width|integer, the width of the image in pixels|
|height|integer, the height of the image in pixels|
|premultiplied|boolean, tells Codea to render this image as a premultiplied image. The default is false.|
|data|string, a sequence of bytes representing the encoded jpeg or png image data.|

======Returns======


The newly created image of given width and height

======Related======

# [[Documentation#image.get|image.get]]
# [[Documentation#image.set|image.set]]
# [[Documentation#image.copy|image.copy]]
# [[Documentation#sprite|sprite]]
# [[Documentation#setcontext|setContext]]

----
=====image.get( x, y )=====
======Examples======

{{{
#!lua
r,g,b,a = myImage:get( 15, 15 )
r,g,b = myImage:get( 25, 25 )
}}}

======Description======


This method returns the red, green, blue and alpha components of the pixel located at x, y in the image.

======Syntax======

{{{
#!lua
image.get( x, y )
}}}

======Parameters======

|=Name|=Description|
|x|integer, x location of the pixel to query|
|y|integer, y location of the pixel to query|

======Returns======


Four values: red, green, blue and alpha representing the color of the pixel at **x**, **y**. The values are in the range 0 to 255.

======Related======

# [[Documentation#image|image]]
# [[Documentation#image.set|image.set]]

----
=====image.set( x, y, color )=====
======Examples======

{{{
#!lua
myImage:set( 15, 15, color(20,30,40,255) )
}}}


{{{
#!lua
myImage:set( 15, 15, 20, 30, 40, 255)
}}}

======Description======


This method sets the red, green, blue and alpha components of the pixel located at x, y. If no alpha parameter is given, it is assumed to be 255.

======Syntax======

{{{
#!lua
image.set( x, y, color )
image.set( x, y, r, g, b, a)
image.set( x, y, r, g, b)
}}}

======Parameters======

|=Name|=Description|
|x|integer, x location of the pixel to query. 1 is the left most column. Must be less than or equal to the image.width value.|
|y|integer, y location of the pixel to query. 1 is the top most row. Must be less than or equal to the image.height value.|
|color|color object, the color to set the pixel to|
|r, g, b, a|integer, the red, green, blue and alpha value to set the pixel to. Between 0 and 255.|

======Related======

# [[Documentation#image|image]]
# [[Documentation#image.set|image.set]]
# [[Documentation#color|color]]

----
=====image.copy( x, y, w, h )=====
======Examples======

{{{
#!lua
newImage = myImage:copy()
}}}


{{{
#!lua
newImage = myImage:copy(20,40,100,100)
}}}

======Description======


This method will copy the pixels in one image into a new image. If no parameters are given, it will copy the whole image, otherwise it will copy the defined subregion. If the region is outside of the image, it will be adjusted to select a valid region from the image. If the rectangle is completely outside of the image, an error will occur.

======Syntax======

{{{
#!lua
image:copy()
image:copy(x, y, width, height)
}}}

======Parameters======

|=Name|=Description|
|x|integer, x location of the leftmost pixels of the copy region.|
|y|integer, y location of the topmost pixels of the copy region|
|width|positive integer, width in pixels of the copy region|
|height|positive integer, height in pixels of the copy region|

======Returns======


The newly created image with a copy of the given image or a subregion of it.

======Related======

# [[Documentation#image|image]]
# [[Documentation#image.set|image.set]]

----
=====mesh=====
======Examples======

{{{
#!lua
-- Create a mesh
myMesh = mesh()

-- Set vertices
myMesh.vertices = {vec3(0,0,0),
                   vec2(100,0,0),
                   vec3(50,100,0)}

-- Set all vertex colors to white
myMesh:setColors(255,255,255,255)
}}}

======Description======


This type represents a triangle mesh. Every three vertices draws a triangle. You can set vertices, texture coordinates and colors. You can also specify a texture using a sprite from a sprite pack or an image.



======Syntax======

{{{
#!lua
m = mesh()
}}}

======Parameters======

|=Name|=Description|
|vertices|table, an array of vec2 or vec3 objects|
|colors|table, an array of color objects. If not set the global fill color is used for all vertices|
|texCoords|table, an array of vec2 objects. If not set, triangles are drawn with color only|
|texture|string or image, the texture to use when drawing this mesh. If not set, triangles are drawn with color only|
|valid|bool, true if this mesh is valid for drawing|
|size|int, number of vertices in this mesh|

======Returns======


The newly created empty mesh

======Related======

# [[Documentation#color|color]]
# [[Documentation#image|image]]
# [[Documentation#spritesize|spriteSize]]
# [[Documentation#sprite|sprite]]
# [[Documentation#vec3|vec3]]
# [[Documentation#vec2|vec2]]

----
=====mesh.draw( m )=====
======Description======


This method draws the **mesh** object. The **mesh** object must be valid to be drawn. For a **mesh** to be valid it must have an equal number of vertices, colors, and texCoords (that are a multiple of three). With the exception that texCoords and / or colors may be nil

======Syntax======

{{{
#!lua
myMesh:draw( m )
}}}

======Parameters======

|=Name|=Description|
|m|the **mesh** to draw|

======Related======

# [[Documentation#mesh|mesh]]

----
=====mesh.setColors( c )=====
======Description======


This method draws the **mesh** object. The **mesh** object must be valid to be drawn. For a **mesh** to be valid it must have an equal number of vertices, colors, and texCoords (that are a multiple of three). With the exception that texCoords and / or colors may be nil

======Syntax======

{{{
#!lua
myMesh:setColors( c )
myMesh:setColors( r, g, b )
myMesh:setColors( r, g, b, a )
}}}

======Parameters======

|=Name|=Description|
|m|the **mesh** to draw|

======Related======

# [[Documentation#mesh|mesh]]

----
=====mesh.clear()=====
======Description======


This method clears a **mesh** removing all vertices, texCoords and colors. The underlying capacity of the **mesh** remain after clearing and this may be preferable to creating a new **mesh**

======Syntax======

{{{
#!lua
myMesh:clear()
}}}

======Related======

# [[Documentation#mesh|mesh]]

----
=====mesh.addRect( x, y, w, h, r )=====
======Description======


This method appends a rectangle centered at the coordinates (x,y) with width, w and height, h. The optional parameter r specifies rotation in radians

======Syntax======

{{{
#!lua
myMesh:addRect( x, y, w, h)
myMesh:addRect( x, y, w, h, r)
}}}

======Parameters======

|=Name|=Description|
|x|float, the x coordinate used to place the rectangle|
|y|float, the y coordinate used to place the rectangle|
|y|float, the y coordinate used to place the rectangle|
|w|float, the width of the rectangle|
|h|float, the height of the rectangle|
|r|float, the rotation of the rectangle|

======Returns======


Returns the index of this rectangle, which can be used to set its position later

======Related======

# [[Documentation#mesh|mesh]]
# [[Documentation#mesh.setrect|mesh.setRect]]

----
=====mesh.setRect( i, x, y, w, h, r )=====
======Description======


This method sets the geometry an existing rectangle with index i, centered at the coordinates (x,y) with width, w and height, h. The optional parameter r specifies rotation in radians

======Syntax======

{{{
#!lua
myMesh:setRect( i, x, y, w, h)
myMesh:setRect( i, x, y, w, h, r)
}}}

======Parameters======

|=Name|=Description|
|i|int, the index of the rectangle in the **mesh**|
|x|float, the x coordinate used to place the rectangle|
|y|float, the y coordinate used to place the rectangle|
|y|float, the y coordinate used to place the rectangle|
|w|float, the width of the rectangle|
|h|float, the height of the rectangle|
|r|float, the rotation of the rectangle|

======Related======

# [[Documentation#mesh|mesh]]
# [[Documentation#mesh.addrect|mesh.addRect]]
# [[Documentation#mesh.setrecttex|mesh.setRectTex]]
# [[Documentation#mesh.setrectcolor|mesh.setRectColor]]

----
=====mesh.setRectTex( i, s, t, w, h )=====
======Description======


This method sets the texture coordinates of an existing rectangle with index i

======Syntax======

{{{
#!lua
myMesh:setRect( i, s, t, w, h)

}}}

======Parameters======

|=Name|=Description|
|i|int, the index of the rectangle in the **mesh**|
|s|float, the left edge of the texture rectangle|
|t|float, the bottom edge of the texture rectangle|
|w|float, the width of the texture rectangle|
|h|float, the height of the texture rectangle|

======Related======

# [[Documentation#mesh|mesh]]
# [[Documentation#mesh.addrect|mesh.addRect]]
# [[Documentation#mesh.setrect|mesh.setRect]]
# [[Documentation#mesh.setrectcolor|mesh.setRectColor]]

----
=====mesh.setRectColor( i, r, g, b )=====
======Description======


This method sets the color of an existing rectangle with index i

======Syntax======

{{{
#!lua
myMesh:setRectColor( i, c)
myMesh:setRectColor( i, r, g, b)
myMesh:setRectColor( i, r, g, b, a)

}}}

======Parameters======

|=Name|=Description|
|i|int, the index of the rectangle in the **mesh**|
|c|color, the color to set the rectangle to|
|r|int, the red component of the color to use|
|g|int, the green component of the color to use|
|b|int, the blue component of the color to use|
|a|int, the alpha component of the color to use|

======Related======

# [[Documentation#mesh|mesh]]
# [[Documentation#mesh.addrect|mesh.addRect]]
# [[Documentation#mesh.setrect|mesh.setRect]]
# [[Documentation#mesh.setrecttex|mesh.setRectTex]]

----
=====mesh.vertex( i )=====
======Description======


When called with one argument, **i**, this method returns the vertex at the index specified by **i**. When called with more arguments, this method sets the vertex at index **i** to the value provided by **x, y, z** or a **vec3** or **vec2**.

\\
This method is useful when you wish to set a single vertex, or small subset of vertices. It is much more efficient than assigning a new vertex table to the mesh.vertices property.



======Syntax======

{{{
#!lua
myMesh:vertex( i )
myMesh:vertex( i, x, y, z )
myMesh:vertex( i, vec3 )
myMesh:vertex( i, x, y )
myMesh:vertex( i, vec2 )
}}}

======Parameters======

|=Name|=Description|
|i|int, the index of the vertex in the **mesh**|
|x|float, the x position to set vertex i to|
|y|float, the y position to set vertex i to|
|z|float, the z position to set vertex i to|
|vec3|vec3, the 3D position to set vertex i to|
|vec2|vec2, the 2D position to set vertex i to|

======Returns======


If called with one argument (the index of the vertex) then this returns a **vec3** value representing the position of the vertex.

======Related======

# [[Documentation#mesh|mesh]]
# [[Documentation#mesh.texcoord|mesh.texCoord]]
# [[Documentation#mesh.color|mesh.color]]

----
=====mesh.texCoord( i )=====
======Description======


When called with one argument, **i**, this method returns the texture coordinate at the index specified by **i**. When called with more arguments, this method sets the texture coordinate at index **i** to the value provided by **x, y** or the given **vec2** value.

\\
This method is useful when you wish to set the texture coordinate of a single vertex, or small subset of vertices. It is much more efficient than assigning a new texture coordinate table to the mesh.texCoords property.



======Syntax======

{{{
#!lua
myMesh:texCoord( i )
myMesh:texCoord( i, x, y )
myMesh:texCoord( i, vec2 )
}}}

======Parameters======

|=Name|=Description|
|i|int, the index of the texture coordinate in the **mesh**|
|x|float, the x value to set vertex i's texture coordinate to|
|y|float, the y value to set vertex i's texture coordinate to|
|vec2|vec2, the texture coordinate value to set on vertex i|

======Returns======


If called with one argument (the index of the vertex) then this returns a **vec2** value representing the texture coordinate at that vertex.

======Related======

# [[Documentation#mesh|mesh]]
# [[Documentation#mesh.vertex|mesh.vertex]]
# [[Documentation#mesh.color|mesh.color]]

----
=====mesh.color( i )=====
======Description======


When called with one argument, **i**, this method returns the color at the index specified by **i**. When called with more arguments, this method sets the color at index **i** to the value provided by **r, g, b, a** or the given **color** object.

\\
This method is useful when you wish to set the color of a single vertex, or small subset of vertices. It is much more efficient than assigning a new color table to the mesh.colors property.



======Syntax======

{{{
#!lua
myMesh:color( i )
myMesh:color( i, r, g, b )
myMesh:color( i, r, g, b, a )
myMesh:color( i, color )
}}}

======Parameters======

|=Name|=Description|
|i|int, the index of the color in the **mesh**|
|r|int, the red value to set vertex i's color to (0 to 255)|
|g|int, the green value to set vertex i's color to (0 to 255)|
|b|int, the blue value to set vertex i's color to (0 to 255)|
|a|int, the alpha value to set vertex i's color to (0 to 255)|
|color|color, the color to set vertex i to|

======Returns======


If called with one argument (the index of the vertex) then this returns a **color** object representing the color at that vertex.

======Related======

# [[Documentation#mesh|mesh]]
# [[Documentation#mesh.vertex|mesh.vertex]]
# [[Documentation#mesh.texcoord|mesh.texCoord]]
# [[Documentation#color|color]]

----
=====triangulate( points )=====
======Description======


Takes an array of points representing a polygon and decomposes it into a list of triangles

======Syntax======

{{{
#!lua
triangleVertices = triangulate( points )
}}}

======Parameters======

|=Name|=Description|
|points|table, an array of vec2 objects representing a polygon|

======Returns======


A triangle list generated from the supplied polygon in the form { t1p1, t1p2, t1p3, t2p1, t2p2, t2p3, ..., tNp3 }

======Related======


----
=====translate( x, y )=====
======Description======


Translates all subsequent drawing operations by the specified **x** and **y** values. Translations are cumulative, so a call to **translate( 50, 0 )** followed by a call to **translate( 10, 10 )** will translate all subsequent drawing operations by **60, 10**. Translate can take an optional **z** parameter to specify depth.



======Syntax======

{{{
#!lua
translate( x, y )
translate( x, y, z )
}}}

======Parameters======

|=Name|=Description|
|x|amount of horizontal translation, in pixels|
|y|amount of vertical translation, in pixels|
|z|amount of depth translation, in pixels|

======Related======

# [[Documentation#rotate|rotate]]
# [[Documentation#scale|scale]]
# [[Documentation#pushmatrix|pushMatrix]]
# [[Documentation#popmatrix|popMatrix]]
# [[Documentation#resetmatrix|resetMatrix]]

----
=====rotate( angle )=====
======Description======


Specifies an amount of rotation (in degrees) to apply to all subsequent drawing. All subsequent drawing functions will be rotated by angle value specified in this function. Rotations are cumulative, so calling **rotate(30)** followed by **rotate(20)** has the same effect as **rotate(50)**.

\\
**rotate()** can also be called with a specific axis, defined by the **x, y, z** parameters. This allows rotation to occur on an arbitrary axis for 3D effects. By default the axis is (0, 0, 1), this means that objects rotate about the axis pointing toward the viewer.



======Syntax======

{{{
#!lua
rotate( angle )
rotate( angle, x, y, z )
}}}

======Parameters======

|=Name|=Description|
|angle|amount of rotation in degrees|
|x|float, x value for the axis of rotation|
|y|float, y value for the axis of rotation|
|z|float, z value for the axis of rotation|

======Related======

# [[Documentation#translate|translate]]
# [[Documentation#scale|scale]]
# [[Documentation#pushmatrix|pushMatrix]]
# [[Documentation#popmatrix|popMatrix]]

----
=====scale( x, y )=====
======Description======


Specifies an amount of scale to apply to all drawing. All subsequent drawing functions will be scaled by the x and y values specified in this function. Scale values are specified as a scalar multipliers, for example, scale(2.0, 2.0) will double the **x** and **y** dimensions of subsequent drawing commands. **scale()** is cumulative, so calling **scale(0.5)** followed by **scale(0.5)** will scale all subsequent drawing operations by 0.25 (i.e., one quarter of their original size).



======Syntax======

{{{
#!lua
scale( amount )
scale( x, y )
scale( x, y, z )
}}}

======Parameters======

|=Name|=Description|
|amount|uniform amount of scale to apply horizontally and vertically. Applies on all axis, x, y and z.|
|x|amount of scale to apply on the x axis (horizontal)|
|y|amount of scale to apply on the y axis (vertical)|
|z|amount of scale to apply on the z axis (depth)|

======Related======

# [[Documentation#rotate|rotate]]
# [[Documentation#translate|translate]]
# [[Documentation#pushmatrix|pushMatrix]]
# [[Documentation#popmatrix|popMatrix]]

----
=====zLevel( z )=====
======Description======


Sets the z level of future drawing operations. Negative values mean the drawing will occur behind (further into the screen), positive values will cause drawing to happen in front. By default all drawing will occur above previous drawing operations.

\\
This property is pushed onto the matrix stack with **pushMatrix()**



======Syntax======

{{{
#!lua
zLevel( z )
}}}

======Parameters======

|=Name|=Description|
|z|float, the amount of depth for future drawing operations, use positive values to draw in front, and negative values to draw behind.|

======Related======

# [[Documentation#transform|transform]]
# [[Documentation#pushmatrix|pushMatrix]]
# [[Documentation#popmatrix|popMatrix]]

----
=====perspective( fov, aspect, near, far )=====
======Description======


Sets the projection matrix to the perspective projection defined by the parameters **fov** (field of view, in degrees), **aspect** (aspect ratio of the screen, defaults to WIDTH/HEIGHT), **near** and **far**. The near and far values specify the closest and farthest distance an object can be without being clipped by the view frustum.

\\
When called without arguments, sets up a perspective projection with a field of view of 45 degrees and an aspect ratio of WIDTH/HEIGHT.

======Syntax======

{{{
#!lua
perspective()
perspective( fov )
perspective( fov, aspect )
perspective( fov, aspect, near, far )
}}}

======Parameters======

|=Name|=Description|
|fov|float, field of view in degrees|
|aspect|float, aspect ratio of the screen. Defaults to WIDTH/HEIGHT|
|near|float, near clipping plane, defaults to 0.1|
|far|float, far clipping plane, default value is computed based on the height of the screen|

======Related======

# [[Documentation#projectionmatrix|projectionMatrix]]
# [[Documentation#ortho|ortho]]
# [[Documentation#camera|camera]]
# [[Documentation#matrix|matrix]]
# [[Documentation#width|WIDTH]]
# [[Documentation#height|HEIGHT]]

----
=====ortho( left, right, bottom, top )=====
======Description======


Sets the projection matrix to the orthographic projection defined by the parameters **left**, **right**, **bottom**, **top**, **near** and **far**. The near and far values specify the closest and farthest distance an object can be without being clipped by the view frustum.

\\
When called with no arguments, sets up the default orthographic projection, equivalent to ortho( 0, WIDTH, 0, HEIGHT, -10, 10 ).



======Syntax======

{{{
#!lua
ortho()
ortho( left, right, bottom, top )
ortho( left, right, bottom, top, near, far )
}}}

======Parameters======

|=Name|=Description|
|left|float, left edge of the frustum|
|right|float, right edge of the frustum|
|bottom|float, bottom edge of the frustum|
|top|float, top edge of the frustum|

======Related======

# [[Documentation#projectionmatrix|projectionMatrix]]
# [[Documentation#perspective|perspective]]
# [[Documentation#camera|camera]]
# [[Documentation#matrix|matrix]]
# [[Documentation#width|WIDTH]]
# [[Documentation#height|HEIGHT]]

----
=====camera(eyeX,eyeY,eyeZ, cX,cY,cZ, upX,upY,upZ)=====
======Description======


Sets the view matrix to the simulate a camera positioned at **eye** and looking at **center**. With an up-vector specified by **up**.

\\
This can be used in conjunction with the **perspective** projection to simulate a camera positioned in 3D space looking at your scene.



======Syntax======

{{{
#!lua
camera( eyeX, eyeY, eyeZ,
        centerX, centerY, centerZ,
        upX, upY, upZ )
}}}

======Parameters======

|=Name|=Description|
|eyeX/Y/Z|floats, position of the "eye" in 3D|
|centerX/Y/Z|floats, coordinate to look at|
|upX/Y/Z|floats, up-vector of the camera, defaults to (0, 1, 0)|

======Related======

# [[Documentation#viewmatrix|viewMatrix]]
# [[Documentation#perspective|perspective]]
# [[Documentation#matrix|matrix]]
# [[Documentation#width|WIDTH]]
# [[Documentation#height|HEIGHT]]

----
=====applyMatrix( matrix )=====
======Description======


Multiplies the matrix specified by **matrix** against the current model matrix. The current model matrix represents the world transform, this is the same matrix used in **pushMatrix** and **popMatrix** operations.



======Syntax======

{{{
#!lua
applyMatrix( matrix )
}}}

======Parameters======

|=Name|=Description|
|matrix|matrix, the transformation to multiply against the current world transform|

======Related======

# [[Documentation#modelmatrix|modelMatrix]]
# [[Documentation#matrix|matrix]]
# [[Documentation#pushmatrix|pushMatrix]]
# [[Documentation#translate|translate]]

----
=====modelMatrix()=====
======Description======


When called with no arguments, returns a **matrix** containing current world transformation. When called with a **matrix** argument, sets the current world transformation to the given matrix.



======Syntax======

{{{
#!lua
modelMatrix()
modelMatrix( matrix )
}}}

======Parameters======

|=Name|=Description|
|matrix|matrix, the transformation to set as the current world transform|

======Returns======


The current model matrix when called with no arguments

======Related======

# [[Documentation#viewmatrix|viewMatrix]]
# [[Documentation#projectionmatrix|projectionMatrix]]
# [[Documentation#matrix|matrix]]
# [[Documentation#pushmatrix|pushMatrix]]

----
=====viewMatrix()=====
======Description======


When called with no arguments, returns a **matrix** containing current view transformation. When called with a **matrix** argument, sets the current view transformation to the given matrix.

\\
The view transform defaults to the identity matrix and is provided as a convenient place to store a camera transform when dealing with 3D scenes. Standard Codea projects do not normally utilise it. See the **camera()** function for a convenient way to set up the view transform.



======Syntax======

{{{
#!lua
viewMatrix()
viewMatrix( matrix )
}}}

======Parameters======

|=Name|=Description|
|matrix|matrix, the transformation to set as the current view transform|

======Returns======


The current view matrix when called with no arguments

======Related======

# [[Documentation#modelmatrix|modelMatrix]]
# [[Documentation#camera|camera]]
# [[Documentation#projectionmatrix|projectionMatrix]]
# [[Documentation#matrix|matrix]]

----
=====projectionMatrix()=====
======Description======


When called with no arguments, returns a **matrix** containing current projection transformation. When called with a **matrix** argument, sets the current projection transformation to the given matrix.

\\
The projection transform defaults to an orthographic projection the width and height of the screen. See the **perspective** and **ortho** functions for more advanced ways to set up the projection matrix.



======Syntax======

{{{
#!lua
projectionMatrix()
projectionMatrix( matrix )
}}}

======Parameters======

|=Name|=Description|
|matrix|matrix, the transformation to set as the current projection transform|

======Returns======


The current projection matrix when called with no arguments

======Related======

# [[Documentation#modelmatrix|modelMatrix]]
# [[Documentation#perspective|perspective]]
# [[Documentation#ortho|ortho]]
# [[Documentation#viewmatrix|viewMatrix]]
# [[Documentation#matrix|matrix]]

----
=====color=====
======Examples======

{{{
#!lua
--Fill with red
c = color( 255, 0, 0 )
fill( c )
}}}

======Description======


This type represents a color with transparency information. You can provide this type as arguments to the style functions **fill()**, **tint()**, **stroke()**, and **background()**.

======Syntax======

{{{
#!lua
color.r
color.g
color.b
color.a
myColor = color( 255, 0, 0, 255 ) --red
}}}

======Parameters======

|=Name|=Description|
|r|float, the red component of this color from 0 to 255|
|g|float, the green component of this color from 0 to 255|
|b|float, the blue component of this color from 0 to 255|
|a|float, the alpha component of this color from 0 to 255|

======Related======

# [[Documentation#fill|fill]]
# [[Documentation#stroke|stroke]]
# [[Documentation#tint|tint]]
# [[Documentation#background|background]]

----
=====ellipseMode( MODE )=====
======Description======


Sets the origin of the ellipses drawn with the **ellipse()** function. The default is **ellipseMode( CENTER )**.

======Syntax======

{{{
#!lua
ellipseMode()
ellipseMode( CENTER|RADIUS|CORNER|CORNERS )
}}}

======Parameters======

|=Name|=Description|
|mode|either CENTER, RADIUS, CORNER or CORNERS\\
\\
**CENTER**  x, y specifies the center of the ellipse, w, h specify its x and y diameter.\\
\\
**RADIUS**  x, y specifies the center of the ellipse, w, h specify its x and y radius.\\
\\
**CORNER**  x, y specifies the lower left corner of the ellipse, w, h specify the size its x and y diameter.\\
\\
**CORNERS**  x, y sets the lower left coordinate of the ellipse’s bounding box. w, h sets the upper right coordinate of the ellipse’s bounding box.|

======Returns======


The current ellipse mode if called without arguments. Returns nothing if called with arguments.

======Related======

# [[Documentation#ellipse|ellipse]]

----
=====rectMode( MODE )=====
======Description======


Sets the origin of the rectangles drawn with the **rect()** function. The default is **rectMode( CORNER )**.

======Syntax======

{{{
#!lua
rectMode()
rectMode( CENTER|RADIUS|CORNER|CORNERS )
}}}

======Parameters======

|=Name|=Description|
|mode|either CENTER, RADIUS, CORNER or CORNERS\\
\\
**CENTER**  x, y specifies the center of the rectangle, w, h specifies the rectangle's width and height.\\
\\
**RADIUS**  x, y specifies the center of the rectangle, w, h specifies half the rectangle's width and height.\\
\\
**CORNER**  x, y specifies the lower left corner of the rectangle, w and h specify the rectangle's width and height.\\
\\
**CORNERS**  x, y sets the lower left coordinate of the rectangle's bounding box. w, h sets the upper right coordinate of the rectangle's bounding box.|

======Returns======


The current rect mode if called without arguments. Returns nothing if called with arguments.

======Related======

# [[Documentation#rect|rect]]

----
=====spriteMode( MODE )=====
======Description======


Sets the origin of the sprites drawn with the **sprite()** function. The default is **spriteMode( CENTER )**.

======Syntax======

{{{
#!lua
spriteMode()
spriteMode( CENTER|RADIUS|CORNER|CORNERS )
}}}

======Parameters======

|=Name|=Description|
|mode|either CENTER, RADIUS, CORNER or CORNERS\\
\\
**CENTER**  x, y specifies the center of the sprite, w, h specifies the sprite's width and height.\\
\\
**RADIUS**  x, y specifies the center of the sprite, w, h specifies half the sprite's width and height.\\
\\
**CORNER**  x, y specifies the lower left corner of the sprite, w and h specify the sprite's width and height.\\
\\
**CORNERS**  x, y sets the lower left coordinate of the sprite's bounding box. w, h sets the upper right coordinate of the sprite's bounding box.|

======Returns======


The current sprite mode if called without arguments. Returns nothing if called with arguments.

======Related======

# [[Documentation#sprite|sprite]]

----
=====spriteSize( name )=====
======Description======


Returns the pixel size of the sprite specified by **name**. If the sprite name is valid this function returns two values, width and height.

======Syntax======

{{{
#!lua
w, h = spriteSize("Planet Cute:Character Boy")
w, h = spriteSize( image )
}}}

======Parameters======

|=Name|=Description|
|name|name of a sprite, in the form "Sprite Pack:Sprite Name"|
|image|image object|

======Returns======


Width and height of the sprite specified by **name**, or image object

======Related======

# [[Documentation#sprite|sprite]]
# [[Documentation#image|image]]

----
=====textMode( MODE )=====
======Description======


Sets the origin of text drawn with the **text()** function. The default is **textMode( CENTER )**.

======Syntax======

{{{
#!lua
textMode()
textMode( CENTER|CORNER )
}}}

======Parameters======

|=Name|=Description|
|mode|either CENTER or CORNER\\
\\
**CENTER**  x, y specifies the center of the text.\\
\\
**CORNER**  x, y specifies the lower left corner of the text.\\
\\
|

======Returns======


The current text mode if called without arguments. Returns nothing if called with arguments.

======Related======

# [[Documentation#text|text]]

----
=====lineCapMode( MODE )=====
======Examples======

{{{
#!lua
background(40, 40, 50)
smooth()
stroke(255)
strokeWidth(15)

translate(WIDTH/2, HEIGHT/2)

lineCapMode(ROUND)
line(-30, -30, -30, 30)
lineCapMode(SQUARE)
line(0, -30, 0, 30)
lineCapMode(PROJECT)
line(30, -30, 30, 30)
}}}

======Description======


Sets the style of the line caps drawn with the **line()** function. The default is **lineCapMode( ROUND )**. Note that **lineCapMode()** only has an effect if **smooth()** is set.

======Syntax======

{{{
#!lua
lineCapMode()
lineCapMode( ROUND | SQUARE | PROJECT )
}}}

======Parameters======

|=Name|=Description|
|mode|either ROUND, SQUARE or PROJECT\\
\\
**ROUND**line ends are rounded with circles

\\
**SQUARE**line ends are squared off at the end points

\\
**PROJECT**line ends are squared off, but project out as far as if they were rounded

\\
|

======Returns======


The current line cap mode if called without arguments. Returns nothing if called with arguments.

======Related======

# [[Documentation#line|line]]
# [[Documentation#stroke|stroke]]
# [[Documentation#strokewidth|strokeWidth]]

----
=====fill( red, green, blue, alpha )=====
======Description======


Sets the color used to fill shapes drawn with the **ellipse()** and **rect()** functions. Also sets the color of text drawn with the **text()** function.

======Syntax======

{{{
#!lua
fill()
fill( gray )
fill( gray, alpha )
fill( red, green, blue )
fill( red, green, blue, alpha )
fill( color )
}}}

======Parameters======

|=Name|=Description|
|gray|int from 0 to 255, specifies value between white and black|
|alpha|int from 0 to 255, specifies opacity of the fill|
|red|int from 0 to 255, specifies red amount of the fill|
|green|int from 0 to 255, specifies green amount of the fill|
|blue|int from 0 to 255, specifies blue amount of the fill|
|color|a value of the color datatype|

======Returns======


Four values (r,g,b,a) representing the current fill color if called without arguments. Returns nothing if called with arguments.

======Related======

# [[Documentation#nofill|noFill]]
# [[Documentation#stroke|stroke]]
# [[Documentation#color|color]]

----
=====noFill()=====
======Description======


Sets the color of the fill to completely transparent.

======Syntax======

{{{
#!lua
noFill()
}}}

======Related======

# [[Documentation#fill|fill]]
# [[Documentation#nostroke|noStroke]]

----
=====tint( red, green, blue, alpha )=====
======Examples======

{{{
#!lua
background(127, 127, 127, 255)
tint(255, 0, 0)
sprite("Planet Cute:Character Boy",
	WIDTH / 2, HEIGHT / 2)
}}}

======Description======


Sets the color used to tint sprites drawn with the **sprite()** function. This color is multiplied with the sprite graphic's color by default.

\\
Setting a white tint with a partial alpha value will make a sprite semi-transparent.



======Syntax======

{{{
#!lua
tint()
tint( gray )
tint( gray, alpha )
tint( red, green, blue )
tint( red, green, blue, alpha )
tint( color )
}}}

======Parameters======

|=Name|=Description|
|gray|int from 0 to 255, specifies value between white and black|
|alpha|int from 0 to 255, specifies opacity of the tint|
|red|int from 0 to 255, specifies red amount of the tint|
|green|int from 0 to 255, specifies green amount of the tint|
|blue|int from 0 to 255, specifies blue amount of the tint|
|color|a value of the color datatype|

======Returns======


Four values (r,g,b,a) representing the current tint color if called without arguments. Returns nothing if called with arguments.

======Related======

# [[Documentation#sprite|sprite]]
# [[Documentation#notint|noTint]]

----
=====noTint()=====
======Description======


Sets the color of the tint to white and completely opaque.

======Syntax======

{{{
#!lua
noTint()
}}}

======Related======

# [[Documentation#tint|tint]]
# [[Documentation#sprite|sprite]]

----
=====stroke( red, green, blue, alpha )=====
======Description======


Sets the color used to outline the shapes drawn with the **ellipse()** and **rect()** functions. Also sets the color of lines drawn with the **line()** function.

======Syntax======

{{{
#!lua
stroke()
stroke( gray )
stroke( gray, alpha )
stroke( red, green, blue )
stroke( red, green, blue, alpha )
stroke( color )
}}}

======Parameters======

|=Name|=Description|
|gray|int from 0 to 255, specifies value between white and black|
|alpha|int from 0 to 255, specifies opacity of the stroke|
|red|int from 0 to 255, specifies red amount of the stroke|
|green|int from 0 to 255, specifies green amount of the stroke|
|blue|int from 0 to 255, specifies blue amount of the stroke|
|color|a value of the color datatype|

======Returns======


Four values (r,g,b,a) representing the current stroke color if called without arguments. Returns nothing if called with arguments.

======Related======

# [[Documentation#strokewidth|strokeWidth]]
# [[Documentation#nostroke|noStroke]]
# [[Documentation#fill|fill]]

----
=====strokeWidth( width )=====
======Description======


Sets the width of the outline of shapes drawn with the **ellipse()** and **rect()** functions. Also sets the width of lines drawn with the **line()** function.

======Syntax======

{{{
#!lua
strokeWidth()
strokeWidth( width )
}}}

======Parameters======

|=Name|=Description|
|width|int or float, the width in pixels of the stroke|

======Returns======


The current stroke width if called without arguments. Returns nothing if called with arguments.

======Related======

# [[Documentation#stroke|stroke]]
# [[Documentation#nostroke|noStroke]]

----
=====noStroke()=====
======Description======


Sets the stroke width to zero.

======Syntax======

{{{
#!lua
noStroke()
}}}

======Related======

# [[Documentation#stroke|stroke]]
# [[Documentation#strokewidth|strokeWidth]]

----
=====smooth()=====
======Description======


This enables smooth line drawing. Lines will appear anti-aliased and respect styles set using the **lineCapMode()** function.

======Syntax======

{{{
#!lua
smooth()
}}}

======Related======

# [[Documentation#nosmooth|noSmooth]]
# [[Documentation#line|line]]
# [[Documentation#linecapmode|lineCapMode]]

----
=====noSmooth()=====
======Description======


This disables smooth line drawing. Lines will appear aliased. Using this option allows you to draw very thin lines clearly.

======Syntax======

{{{
#!lua
noSmooth()
}}}

======Related======

# [[Documentation#smooth|smooth]]
# [[Documentation#line|line]]
# [[Documentation#linecapmode|lineCapMode]]

----
=====font( name )=====
======Description======


This sets the current font to the font specified by **name**. If no argument is given **font()** returns the current font. The default font is "Helvetica".

======Syntax======

{{{
#!lua
font()
font( name )
}}}

======Parameters======

|=Name|=Description|
|name|string, the name of the font to use. For iOS devices, this can be one of the following:

\\

{{{
#!lua
AcademyEngravedLetPlain\nAmericanTypewriter-CondensedLight\nAmericanTypewriter-Light\nAmericanTypewriter\nAmericanTypewriter-Condensed\nAmericanTypewriter-Bold\nAmericanTypewriter-CondensedBold\nAppleColorEmoji\nAppleSDGothicNeo-Medium\nAppleSDGothicNeo-Bold\nArialMT\nArial-ItalicMT\nArial-BoldMT\nArial-BoldItalicMT\nArialHebrew\nArialHebrew-Bold\nBangalaSangamMN-Bold\nBangalaSangamMN\nBaskerville\nBaskerville-Italic\nBaskerville-SemiBold\nBaskerville-SemiBoldItalic\nBaskerville-Bold\nBaskerville-BoldItalic\nBodoniSvtyTwoITCTT-Book\nBodoniSvtyTwoITCTT-BookIta\nBodoniSvtyTwoITCTT-Bold\nBodoniSvtyTwoOSITCTT-Book\nBodoniSvtyTwoOSITCTT-BookIt\nBodoniSvtyTwoOSITCTT-Bold\nBodoniSvtyTwoSCITCTT-Book\nBodoniOrnamentsITCTT\nBradleyHandITCTT-Bold\nChalkboardSE-Light\nChalkboardSE-Regular\nChalkboardSE-Bold\nChalkduster\nCopperplate-Light\nCopperplate\nCopperplate-Bold\nCourier\nCourier-Oblique\nCourier-Bold\nCourier-BoldOblique\nCourierNewPSMT\nCourierNewPS-BoldMT\nCourierNewPS-BoldItalicMT\nCourierNewPS-ItalicMT\nDBLCDTempBlack\nDevanagariSangamMN\nDevanagariSangamMN-Bold\nDidot\nDidot-Italic\nDidot-Bold\nEuphemiaUCAS\nEuphemiaUCAS-Italic\nEuphemiaUCAS-Bold\nFutura-Medium\nFutura-MediumItalic\nFutura-CondensedMedium\nFutura-CondensedExtraBold\nGeezaPro\nGeezaPro-Bold\nGeorgia\nGeorgia-Italic\nGeorgia-Bold\nGeorgia-BoldItalic\nGillSans-Light\nGillSans-LightItalic\nGillSans\nGillSans-Italic\nGillSans-Bold\nGillSans-BoldItalic\nGujaratiSangamMN\nGujaratiSangamMN-Bold\nGurmukhiMN\nGurmukhiMN-Bold\nSTHeitiSC-Light\nSTHeitiSC-Medium\nSTHeitiTC-Light\nSTHeitiTC-Medium\nHelvetica-Light\nHelvetica-LightOblique\nHelvetica\nHelvetica-Oblique\nHelvetica-Bold\nHelvetica-BoldOblique\nHelveticaNeue-UltraLight\nHelveticaNeue-UltraLightItalic\nHelveticaNeue-Light\nHelveticaNeue-LightItalic\nHelveticaNeue\nHelveticaNeue-Italic\nHelveticaNeue-Medium\nHelveticaNeue-Bold\nHelveticaNeue-BoldItalic\nHelveticaNeue-CondensedBold\nHelveticaNeue-CondensedBlack\nHiraKakuProN-W3\nHiraKakuProN-W6\nHiraMinProN-W3\nHiraMinProN-W6\nHoeflerText-Regular\nHoeflerText-Italic\nHoeflerText-Black\nHoeflerText-BlackItalic\nKailasa\nKailasa-Bold\nKannadaSangamMN\nKannadaSangamMN-Bold\nMalayalamSangamMN\nMalayalamSangamMN-Bold\nMarion-Regular\nMarion-Italic\nMarion-Bold\nMarkerFelt-Thin\nMarkerFelt-Wide\nNoteworthy-Light\nNoteworthy-Bold\nOptima-Italic\nOptima-Regular\nOptima-Bold\nOptima-BoldItalic\nOptima-ExtraBlack\nOriyaSangamMN\nOriyaSangamMN-Bold\nPalatino-Roman\nPalatino-Italic\nPalatino-Bold\nPalatino-BoldItalic\nPapyrus\nPapyrus-Condensed\nPartyLetPlain\nSinhalaSangamMN\nSinhalaSangamMN-Bold\nSnellRoundhand\nSnellRoundhand-Bold\nSnellRoundhand-Black\nTamilSangamMN\nTamilSangamMN-Bold\nTeluguSangamMN\nTeluguSangamMN-Bold\nThonburi\nThonburi-Bold\nTimesNewRomanPSMT\nTimesNewRomanPS-ItalicMT\nTimesNewRomanPS-BoldMT\nTimesNewRomanPS-BoldItalicMT\nTrebuchetMS\nTrebuchetMS-Italic\nTrebuchetMS-Bold\nTrebuchetMS-BoldItalic\nVerdana\nVerdana-Italic\nVerdana-Bold\nVerdana-BoldItalic\nZapfDingbatsITC\nZapfino
}}}


|

======Returns======


The current font if called without arguments. Returns nothing if called with arguments.

======Related======

# [[Documentation#text|text]]
# [[Documentation#fontsize|fontSize]]

----
=====fontSize( size )=====
======Description======


This sets the current font size to the size specified by **size**. If no argument is given **fontSize()** returns the current font size. The default font size is 17 points.

======Syntax======

{{{
#!lua
fontSize()
fontSize( size )
}}}

======Parameters======

|=Name|=Description|
|size|float, the size of the font (in points). Must be greater than 0.0.|

======Returns======


The current font size if called without arguments. Returns nothing if called with arguments.

======Related======

# [[Documentation#text|text]]
# [[Documentation#font|font]]

----
=====fontMetrics()=====
======Description======


This function returns a table of font metrics for the currently defined font (as defined by **font()** and **fontSize()**). The metrics table contains advanced information about the font's measurements, such as ascent, leading, x height, and so on.

\\
Please note that this function only works on iOS 5 and above.



======Syntax======

{{{
#!lua
fontMetrics()
}}}

======Returns======


A table containing the following keys:**\\
ascent\\
descent\\
leading\\
xHeight\\
capHeight\\
underlinePosition\\
underlineThickness\\
slantAngle\\
size

**

======Related======

# [[Documentation#font|font]]
# [[Documentation#fontsize|fontSize]]

----
=====textAlign( ALIGN )=====
======Description======


This sets the alignment of text rendered with the **text()** function. This is generally used in conjunction with **textWrapWidth()** to produce multi-line, word-wrapped text aligned to the LEFT, CENTER or RIGHT. If called without arguments this function returns the current text alignment. The default text alignment is **textAlign( LEFT )**.

======Syntax======

{{{
#!lua
textAlign()
textAlign( LEFT|CENTER|RIGHT )
}}}

======Parameters======

|=Name|=Description|
|ALIGN|Can be LEFT, CENTER or RIGHT|

======Returns======


The current text alignment if called without arguments. Returns nothing if called with arguments.

======Related======

# [[Documentation#text|text]]
# [[Documentation#textwrapwidth|textWrapWidth]]

----
=====textWrapWidth( width )=====
======Examples======

{{{
#!lua
background(100, 120, 160)
font("Georgia")
fill(255)
fontSize(20)
textWrapWidth(70)
text("Hello World!", WIDTH/2, HEIGHT/2)
}}}

======Description======


This sets the wrap width, in pixels, of text rendered with **text()**. If set to a value greater than 0, it causes text to wrap onto the next line when the line's width exceeds the specified **width**. When this is called without arguments, it returns the current text wrap width. The default text wrap width is 0, which indicates no wrapping, and that text should be rendered on one line.

======Syntax======

{{{
#!lua
textWrapWidth()
textWrapWidth( width )
}}}

======Parameters======

|=Name|=Description|
|width|float, width before the text rendered by **text()** word-wraps|

======Returns======


The current text wrap width if called without arguments. Returns nothing if called with arguments.

======Related======

# [[Documentation#text|text]]
# [[Documentation#textalign|textAlign]]

----
=====textSize( string )=====
======Examples======

{{{
#!lua
background(100, 120, 160)
font("Georgia")
fontSize(20)
textWrapWidth(70)

-- Get the dimensions of our string
w,h = textSize("Hello World!")

-- Draw a box behind our text
fill(120,0,40)
strokeWidth(2)
rectMode(CENTER)
rect(WIDTH/2,HEIGHT/2,w+15,h+15)

fill(255)
text("Hello World!",WIDTH/2,HEIGHT/2)
}}}

======Description======


This function returns the dimensions of the specified string when rendered with the current font size and style. Note that this function returns two values: width and height. You can use these dimensions to, for example, render a button behind a piece of text, position text within a speech bubble, and so on.



======Syntax======

{{{
#!lua
width = textSize( string )
width, height = textSize( string )
}}}

======Parameters======

|=Name|=Description|
|string|string, the string to measure|

======Returns======


width and height of the text string when rendered with the current font size and style.

======Related======

# [[Documentation#text|text]]

----
=====pushMatrix()=====
======Description======


The **pushMatrix()** function saves any transformations that have been made and pushes a copy of them onto the top of the stack. You can then perform further transforms (translations, rotations and scales), perform drawing operations, and return to the previous transformation by calling **popMatrix()**. You can nest calls to **pushMatrix()** and **popMatrix()** for more complex object placement.

\\
The following transform calls are preserved when using **pushMatrix()** and **popMatrix()**: translate(), rotate(), scale()



======Syntax======

{{{
#!lua
pushMatrix()
}}}

======Related======

# [[Documentation#popmatrix|popMatrix]]
# [[Documentation#resetmatrix|resetMatrix]]
# [[Documentation#translate|translate]]
# [[Documentation#rotate|rotate]]
# [[Documentation#scale|scale]]

----
=====popMatrix()=====
======Description======


The **pMatrix()** function saves any transformations that have been made and pushes a copy of them onto the top of the stack. You can then perform further transforms (translations, rotations and scales), perform drawing operations, and return to the previous transformation by calling **popMatrix()**. You can nest calls to **pushMatrix()** and **popMatrix()** for more complex object placement.

\\
The following transform calls are preserved when using **pushMatrix()** and **popMatrix()**: translate(), rotate(), scale()



======Syntax======

{{{
#!lua
popMatrix()
}}}

======Related======

# [[Documentation#pushmatrix|pushMatrix]]
# [[Documentation#resetmatrix|resetMatrix]]
# [[Documentation#translate|translate]]
# [[Documentation#rotate|rotate]]
# [[Documentation#scale|scale]]

----
=====popMatrix()=====
======Description======


The **pMatrix()** function saves any transformations that have been made and pushes a copy of them onto the top of the stack. You can then perform further transforms (translations, rotations and scales), perform drawing operations, and return to the previous transformation by calling **popMatrix()**. You can nest calls to **pushMatrix()** and **popMatrix()** for more complex object placement.

\\
The following transform calls are preserved when using **pushMatrix()** and **popMatrix()**: translate(), rotate(), scale()



======Syntax======

{{{
#!lua
popMatrix()
}}}

======Related======

# [[Documentation#pushmatrix|pushMatrix]]
# [[Documentation#resetmatrix|resetMatrix]]

----
=====resetMatrix()=====
======Description======


This function resets all transformation. It replaces the current transform matrix with the identity matrix. This effectively repositions all drawing at 0, 0, with no rotation and scaling.



======Syntax======

{{{
#!lua
resetMatrix()
}}}

======Related======

# [[Documentation#pushmatrix|pushMatrix]]
# [[Documentation#popmatrix|popMatrix]]
# [[Documentation#translate|translate]]
# [[Documentation#rotate|rotate]]
# [[Documentation#scale|scale]]

----
=====pushStyle()=====
======Description======


The **pushStyle()** function saves the current graphics style and pushes a copy of the current style onto the top of the stack. You can then modify the style, perform drawing operations, and return to the previous style by calling **popStyle()**. You can nest calls to **pushStyle()** and **popStyle()** in order to provide more control.

\\
Styles set with the following functions are preserved when using **pushStyle()** and **popStyle()**: fill(), noFill(), stroke(), noStroke(), tint(), noTint(), strokeWidth(), lineCapMode(), ellipseMode(), rectMode(), spriteMode(), smooth(), noSmooth()



======Syntax======

{{{
#!lua
pushStyle()
}}}

======Related======

# [[Documentation#popstyle|popStyle]]
# [[Documentation#resetstyle|resetStyle]]

----
=====popStyle()=====
======Description======


The **pushStyle()** function saves the current graphics style and pushes a copy of the current style onto the top of the stack. You can then modify the style, perform drawing operations, and return to the previous style by calling **popStyle()**. You can nest calls to **pushStyle()** and **popStyle()** in order to provide more control.

\\
Styles set with the following functions are preserved when using **pushStyle()** and **popStyle()**: fill(), noFill(), stroke(), noStroke(), tint(), noTint(), strokeWidth(), lineCapMode(), ellipseMode(), rectMode(), spriteMode(), smooth(), noSmooth()



======Syntax======

{{{
#!lua
popStyle()
}}}

======Related======

# [[Documentation#pushstyle|pushStyle]]
# [[Documentation#resetstyle|resetStyle]]

----
=====resetStyle()=====
======Description======


Calling **resetStyle()** will reset all style parameters to their default values. This will effect whatever style is currently on the top of the stack.

\\
Styles set with the following functions are reset when using **resetStyle()**: fill(), noFill(), stroke(), noStroke(), tint(), noTint(), strokeWidth(), lineCapMode(), ellipseMode(), rectMode(), spriteMode(), smooth(), noSmooth()



======Syntax======

{{{
#!lua
resetStyle()
}}}

======Related======

# [[Documentation#pushstyle|pushStyle]]
# [[Documentation#popstyle|popStyle]]

----
=====WIDTH=====
======Description======


This constant is set to the width of the screen in pixels.

======Syntax======

{{{
#!lua
WIDTH
}}}

======Returns======


Width of the screen in pixels

======Related======

# [[Documentation#height|HEIGHT]]

----
=====HEIGHT=====
======Description======


This constant is set to the height of the screen in pixels.

======Syntax======

{{{
#!lua
HEIGHT
}}}

======Returns======


Height of the screen in pixels

======Related======

# [[Documentation#width|WIDTH]]

----
=====ElapsedTime=====
======Description======


Query this variable to get the current elapsed time, in seconds, while running your project.

======Syntax======

{{{
#!lua
ElapsedTime
}}}

======Returns======


Time in seconds since the start of running the project

======Related======

# [[Documentation#deltatime|DeltaTime]]

----
=====DeltaTime=====
======Description======


Query this variable to get the time elapsed, in seconds, since the last draw call while running your project.

======Syntax======

{{{
#!lua
DeltaTime
}}}

======Returns======


Time in seconds since the start of the previous frame

======Related======

# [[Documentation#elapsedtime|ElapsedTime]]

----
=====ContentScaleFactor=====
======Description======


Query this variable to get the content scale factor. This specifies the internal scaling of images and sprites. On retina devices this will be equal to **2**, on non-retina devices it will be equal to **1**.

======Syntax======

{{{
#!lua
ContentScaleFactor
}}}

======Returns======


Content scale factor of the viewer


----
===Lua===
====Tables, Strings, Math and Time====

----
=====For Loops Overview=====
======Description======


You can use **for loops** in Lua to iterate over arrays and tables, performing tasks for each element.

\\
This example simply iterates i over the values 1 to 10


{{{
#!lua
-- Iterate from 1 to 10
for i = 1, 10 do
    print( i )
end
}}}


\\
This example uses the **ipairs** function to sequentially iterate over a table. Note that ipairs only works on tables that have sequential elements beginning at 1.


{{{
#!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
}}}


\\
This example uses **pairs** to iterate over all the key/value pairs in a table, unlike **ipairs** the keys do not have to be integral values, and can be anything.


{{{
#!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
}}}




======Related======

# [[Documentation#ipairs|ipairs]]
# [[Documentation#pairs|pairs]]

----
=====Conditionals Overview=====
======Description======


Use **conditionals** to test for a particular circumstance and then branch your code appropriately. See the examples below.

\\

{{{
#!lua
-- Check if x is equal to 10
if x == 10 then
    print( "x equals 10" )
end
}}}


\\

{{{
#!lua
-- 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
}}}


\\

{{{
#!lua
-- 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
}}}





----
=====ipairs( table )=====
======Description======


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



======Syntax======

{{{
#!lua
for i,v in ipairs( t ) do body end

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

======Parameters======

|=Name|=Description|
|table|table to iterate over|

======Returns======


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

======Related======

# [[Documentation#forloops|forloops]]
# [[Documentation#pairs|pairs]]

----
=====pairs( table )=====
======Description======


**pairs** can be used to iterate over a table's key-value pairs.

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



======Syntax======

{{{
#!lua
for k,v in pairs( t ) do body end

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

======Parameters======

|=Name|=Description|
|table|table to iterate over|

======Returns======


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

======Related======

# [[Documentation#forloops|forloops]]
# [[Documentation#ipairs|ipairs]]

----
=====table.concat( table, sep )=====
======Description======


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.



======Syntax======

{{{
#!lua
table.concat( table )
table.concat( table, sep )
table.concat( table, sep, i )
table.concat( table, sep, i, j )
}}}

======Parameters======

|=Name|=Description|
|table|table to concatenate|
|sep|separator string|
|i|int, starting index to concatenate from|
|j|int, ending index|

======Returns======


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


----
=====table.insert( table, pos, value )=====
======Description======


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.



======Syntax======

{{{
#!lua
table.insert( table, value )
table.insert( table, pos, value )
}}}

======Parameters======

|=Name|=Description|
|table|table to insert into|
|pos|int, position to inset|
|value|value to insert|

======Related======

# [[Documentation#table.remove|table.remove]]

----
=====table.maxn( table )=====
======Description======


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



======Syntax======

{{{
#!lua
table.maxn( table )
}}}

======Parameters======

|=Name|=Description|
|table|table to query|

======Returns======


Largest positive numerical index of the given table


----
=====table.remove( table, pos )=====
======Description======


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.



======Syntax======

{{{
#!lua
table.remove( table )
table.remove( table, pos )
}}}

======Parameters======

|=Name|=Description|
|table|table to insert into|
|pos|int, position of value to remove|

======Returns======


Value of the removed element

======Related======

# [[Documentation#table.insert|table.insert]]

----
=====table.sort( table )=====
======Description======


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.



======Syntax======

{{{
#!lua
table.sort( table )
table.sort( table, comp )
}}}

======Parameters======

|=Name|=Description|
|table|the table to sort|
|comp|a function that receives two table elements and returns true when the first is less than the second|


----
=====os.clock()=====
======Description======


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



======Syntax======

{{{
#!lua
os.clock()
}}}

======Returns======


Approximation of the amount in seconds of CPU time used by the program.


----
=====os.difftime( t2, t1 )=====
======Description======


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



======Syntax======

{{{
#!lua
os.difftime( t2, t1 )
}}}

======Parameters======

|=Name|=Description|
|t2|Ending time|
|t1|Starting time|

======Returns======


Number of seconds from time **t1** to time **t2**.

======Related======

# [[Documentation#os.time|os.time]]

----
=====os.date( format )=====
======Description======


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



======Syntax======

{{{
#!lua
os.date()
os.date( format )
os.date( format, time )
}}}

======Parameters======

|=Name|=Description|
|format|String used to format the returned date|
|time|If the time argument is present, this is the time to be formatted (see the os.time function for a description of this value).|

======Returns======


A string or a table containing the date and time.

======Related======

# [[Documentation#os.time|os.time]]
# [[Documentation#os.setlocale|os.setlocale]]

----
=====os.setlocale( locale )=====
======Description======


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.



======Syntax======

{{{
#!lua
os.setlocale( locale )
os.setlocale( locale, category )
}}}

======Parameters======

|=Name|=Description|
|locale|String specifying a locale, can be nil or the empty string.|
|category|String specifying a category to set, can be "all", "collate", "ctype", "monetary", "numeric", or "time"|

======Returns======


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

======Related======

# [[Documentation#os.date|os.date]]
# [[Documentation#os.time|os.time]]

----
=====os.time()=====
======Description======


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



======Syntax======

{{{
#!lua
os.time()
os.time( table )
}}}

======Parameters======

|=Name|=Description|
|table|This table must have fields **year**, **month**, and **day**, and may have fields **hour**, **min**, **sec**, and **isdst**|

======Returns======


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

======Related======

# [[Documentation#os.date|os.date]]
# [[Documentation#os.setlocale|os.setlocale]]
# [[Documentation#os.difftime|os.difftime]]

----
=====string.find( s, pattern )=====
======Description======


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.



======Syntax======

{{{
#!lua
string.find( s, pattern )
string.find( s, pattern, init )
string.find( s, pattern, init, plain )
}}}

======Parameters======

|=Name|=Description|
|s|string to search in|
|pattern|pattern to look for|
|init|starting character in string to search from, default is 1|
|plain|boolean, perform a plain substring search|

======Returns======


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


----
=====string.format( formatstring, ... )=====
======Examples======

{{{
#!lua
s = string.format("Number is %d", 5)
print( s )
-- prints "Number is 5"
}}}

======Description======


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.



======Syntax======

{{{
#!lua
string.format( formatstring, ... )
}}}

======Parameters======

|=Name|=Description|
|formatstring|string defining the format|

======Returns======


A formatted string


----
=====string.len( s )=====
======Description======


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



======Syntax======

{{{
#!lua
string.len( s )
}}}

======Parameters======

|=Name|=Description|
|s|get the length of this string|

======Returns======


Length of string **s**


----
=====string.lower( s )=====
======Description======


Receives a string and returns a copy of this string with all uppercase letters changed to lowercase. All other characters are left unchanged.



======Syntax======

{{{
#!lua
string.lower( s )
}}}

======Parameters======

|=Name|=Description|
|s|get a lowercase version of this string|

======Returns======


Lowercase version of string **s**

======Related======

# [[Documentation#string.upper|string.upper]]

----
=====string.upper( s )=====
======Description======


Receives a string and returns a copy of this string with all lowercase letters changed to uppercase. All other characters are left unchanged.



======Syntax======

{{{
#!lua
string.upper( s )
}}}

======Parameters======

|=Name|=Description|
|s|get an uppercase version of this string|

======Returns======


Uppercase version of string **s**

======Related======

# [[Documentation#string.lower|string.lower]]

----
=====string.match( s, pattern )=====
======Description======


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.



======Syntax======

{{{
#!lua
string.match( s, pattern )
string.match( s, pattern, init )
}}}

======Parameters======

|=Name|=Description|
|s|string to search|
|pattern|pattern to match|
|init|starting location in string|

======Returns======


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

======Related======

# [[Documentation#string.find|string.find]]

----
=====string.rep( s, n )=====
======Description======


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



======Syntax======

{{{
#!lua
string.rep( s, n )
}}}

======Parameters======

|=Name|=Description|
|s|string to replicate|
|n|int, number of times to replicate the string|

======Returns======


**n** concatenations of string **s**


----
=====string.sub( s, i, j )=====
======Description======


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



======Syntax======

{{{
#!lua
string.sub( s, i )
string.sub( s, i, j )
}}}

======Parameters======

|=Name|=Description|
|s|find substring of this string|
|i|int, starting index|
|j|int, ending index|

======Returns======


Substring of string **s**


----
=====math.abs( value )=====
======Description======


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

======Syntax======

{{{
#!lua
math.abs( value )
}}}

======Parameters======

|=Name|=Description|
|value|int or float, the number to get the absolute value of|

======Returns======


The absolute value of value


----
=====math.acos( value )=====
======Description======


This function returns the arc cosine of **value** in radians

======Syntax======

{{{
#!lua
math.acos( value )
}}}

======Parameters======

|=Name|=Description|
|value|int or float, compute the arc cosine of this number|

======Returns======


The arc cosine of value in radians

======Related======

# [[Documentation#math.asin|math.asin]]
# [[Documentation#math.atan|math.atan]]
# [[Documentation#math.atan2|math.atan2]]

----
=====math.asin( value )=====
======Description======


This function returns the arc sine of **value** in radians

======Syntax======

{{{
#!lua
math.asin( value )
}}}

======Parameters======

|=Name|=Description|
|value|int or float, compute the arc sine of this number|

======Returns======


The arc sine of value in radians

======Related======

# [[Documentation#math.acos|math.acos]]
# [[Documentation#math.atan|math.atan]]
# [[Documentation#math.atan2|math.atan2]]

----
=====math.atan( value )=====
======Description======


This function returns the arc tangent of **value** in radians

======Syntax======

{{{
#!lua
math.atan( value )
}}}

======Parameters======

|=Name|=Description|
|value|int or float, compute the arc tangent of this number|

======Returns======


The arc tangent of value in radians

======Related======

# [[Documentation#math.asin|math.asin]]
# [[Documentation#math.acos|math.acos]]
# [[Documentation#math.atan2|math.atan2]]

----
=====math.atan2( x, y )=====
======Description======


This function returns the arc tangent of y/x in radians, but uses the sign of both parameters to find the quadrant of the result. It also handles correctly the case of x being zero.

======Syntax======

{{{
#!lua
math.atan2( x, y )
}}}

======Parameters======

|=Name|=Description|
|x|int or float, denominator for arc tangent|
|y|int or float, numerator for arc tangent|

======Returns======


The arc tangent of y/x in radians

======Related======

# [[Documentation#math.asin|math.asin]]
# [[Documentation#math.acos|math.acos]]
# [[Documentation#math.atan|math.atan]]

----
=====math.ceil( value )=====
======Description======


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.

======Syntax======

{{{
#!lua
math.ceil( value )
}}}

======Parameters======

|=Name|=Description|
|value|int or float, compute the smallest integer larger than or equal to this number|

======Returns======


The smallest integer larger than or equal to value

======Related======

# [[Documentation#math.floor|math.floor]]

----
=====math.cos( value )=====
======Description======


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

======Syntax======

{{{
#!lua
math.cos( value )
}}}

======Parameters======

|=Name|=Description|
|value|int or float, compute the cosine of this number|

======Returns======


Cosine of value

======Related======

# [[Documentation#math.sin|math.sin]]
# [[Documentation#math.tan|math.tan]]

----
=====math.cosh( value )=====
======Description======


This function returns hyperbolic cosine of value.

======Syntax======

{{{
#!lua
math.cosh( value )
}}}

======Parameters======

|=Name|=Description|
|value|int or float, compute the hyperbolic cosine of this number|

======Returns======


Hyperbolic cosine of value

======Related======

# [[Documentation#math.sinh|math.sinh]]
# [[Documentation#math.tanh|math.tanh]]

----
=====math.deg( value )=====
======Description======


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

======Syntax======

{{{
#!lua
math.deg( value )
}}}

======Parameters======

|=Name|=Description|
|value|int or float, angle in radians to convert to degrees|

======Returns======


Angle specified by value (in radians) in degrees

======Related======

# [[Documentation#math.rad|math.rad]]

----
=====math.rad( value )=====
======Description======


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

======Syntax======

{{{
#!lua
math.rad( value )
}}}

======Parameters======

|=Name|=Description|
|value|int or float, angle in degrees to convert to radians|

======Returns======


Angle specified by value (in degrees) in radians

======Related======

# [[Documentation#math.deg|math.deg]]

----
=====math.exp( value )=====
======Description======


This function returns e raised to value

======Syntax======

{{{
#!lua
math.exp( value )
}}}

======Parameters======

|=Name|=Description|
|value|int or float, exponent of e|

======Returns======


e raised to the power of value


----
=====math.floor( value )=====
======Description======


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.

======Syntax======

{{{
#!lua
math.floor( value )
}}}

======Parameters======

|=Name|=Description|
|value|int or float, compute the largest integer smaller than or equal to this number|

======Returns======


The largest integer smaller than or equal to value

======Related======

# [[Documentation#math.ceil|math.ceil]]

----
=====math.fmod( x, y )=====
======Description======


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

======Syntax======

{{{
#!lua
math.fmod( x, y )
}}}

======Parameters======

|=Name|=Description|
|x|int or float|
|y|int or float|

======Returns======


The remainder of the division of x by y

======Related======

# [[Documentation#math.modf|math.modf]]

----
=====math.frexp( value )=====
======Description======


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

======Syntax======

{{{
#!lua
math.frexp( value )
}}}

======Parameters======

|=Name|=Description|
|value|int or float|

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

======Related======

# [[Documentation#math.ldexp|math.ldexp]]

----
=====math.ldexp( m, e )=====
======Description======


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

======Syntax======

{{{
#!lua
math.ldexp( m, e )
}}}

======Parameters======

|=Name|=Description|
|m|int or float|
|m|int|

======Returns======


m2^e

======Related======

# [[Documentation#math.frexp|math.frexp]]

----
=====math.log( value )=====
======Description======


This function returns the natural logarithm of value

======Syntax======

{{{
#!lua
math.log( value )
}}}

======Parameters======

|=Name|=Description|
|value|int or float, compute the natural logarithm of this value|

======Returns======


The natural logarithm of value

======Related======

# [[Documentation#math.log10|math.log10]]

----
=====math.log10( value )=====
======Description======


This function returns the base-10 logarithm of value

======Syntax======

{{{
#!lua
math.log10( value )
}}}

======Parameters======

|=Name|=Description|
|value|int or float, compute the base-10 logarithm of this value|

======Returns======


The base-10 logarithm of value

======Related======

# [[Documentation#math.log|math.log]]

----
=====math.max( value, ... )=====
======Description======


This function returns maximum value among its arguments.

======Syntax======

{{{
#!lua
math.max( value, ... )
}}}

======Parameters======

|=Name|=Description|
|value|any comparable value|

======Returns======


The maximum value among its arguments

======Related======

# [[Documentation#math.min|math.min]]

----
=====math.min( value, ... )=====
======Description======


This function returns minimum value among its arguments.

======Syntax======

{{{
#!lua
math.min( value, ... )
}}}

======Parameters======

|=Name|=Description|
|value|any comparable value|

======Returns======


The minimum value among its arguments

======Related======

# [[Documentation#math.max|math.max]]

----
=====math.modf( value )=====
======Description======


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

======Syntax======

{{{
#!lua
math.modf( value )
}}}

======Parameters======

|=Name|=Description|
|value|int or float|

======Returns======


Two numbers, the integral part of value and the fractional part of value

======Related======

# [[Documentation#math.fmod|math.fmod]]

----
=====math.pow( x, y )=====
======Description======


This function returns x raised to y. Equivalent to the expression x^y.

======Syntax======

{{{
#!lua
math.pow( x, y )
}}}

======Parameters======

|=Name|=Description|
|x|int or float|
|y|int or float|

======Returns======


x raised to y

======Related======

# [[Documentation#math.sqrt|math.sqrt]]

----
=====math.random()=====
======Description======


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

======Syntax======

{{{
#!lua
math.random()
math.random( maximum )
math.random( minimum, maximum )
}}}

======Parameters======

|=Name|=Description|
|minimum|int, minimum value of returned pseudo-random number|
|maximum|int, maximum value of returned pseudo-random number|

======Returns======


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

======Related======

# [[Documentation#math.randomseed|math.randomseed]]

----
=====math.randomseed( value )=====
======Description======


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

======Syntax======

{{{
#!lua
math.randomseed( value )
}}}

======Parameters======

|=Name|=Description|
|value|int, seed of the pseudo-random number generator|

======Returns======


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

======Related======

# [[Documentation#math.random|math.random]]

----
=====math.sin( value )=====
======Description======


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

======Syntax======

{{{
#!lua
math.sin( value )
}}}

======Parameters======

|=Name|=Description|
|value|int or float, compute the sine of this number|

======Returns======


Sine of value

======Related======

# [[Documentation#math.cos|math.cos]]
# [[Documentation#math.tan|math.tan]]

----
=====math.sinh( value )=====
======Description======


This function returns hyperbolic sine of value.

======Syntax======

{{{
#!lua
math.sinh( value )
}}}

======Parameters======

|=Name|=Description|
|value|int or float, compute the hyperbolic sine of this number|

======Returns======


Hyperbolic sine of value

======Related======

# [[Documentation#math.cosh|math.cosh]]
# [[Documentation#math.tanh|math.tanh]]

----
=====math.tan( value )=====
======Description======


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

======Syntax======

{{{
#!lua
math.tan( value )
}}}

======Parameters======

|=Name|=Description|
|value|int or float, compute the tangent of this number|

======Returns======


Tangent of value

======Related======

# [[Documentation#math.sin|math.sin]]
# [[Documentation#math.cos|math.cos]]

----
=====math.tanh( value )=====
======Description======


This function returns hyperbolic tangent of value.

======Syntax======

{{{
#!lua
math.tanh( value )
}}}

======Parameters======

|=Name|=Description|
|value|int or float, compute the hyperbolic tangent of this number|

======Returns======


Hyperbolic tangent of value

======Related======

# [[Documentation#math.sinh|math.sinh]]
# [[Documentation#math.cosh|math.cosh]]

----
=====math.sqrt( value )=====
======Description======


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

======Syntax======

{{{
#!lua
math.sqrt( value )
}}}

======Parameters======

|=Name|=Description|
|value|int or float, compute the square root of this number|

======Returns======


Square root of value

======Related======

# [[Documentation#math.pow|math.pow]]

----
=====math.huge=====
======Description======


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

======Syntax======

{{{
#!lua
math.huge
}}}

======Returns======


A value larger than or equal to any other numerical value


----
=====math.pi=====
======Description======


The value of pi.

======Syntax======

{{{
#!lua
math.pi
}}}

======Returns======


Value of pi


----
===Touch===
====Detecting and Reacting to Touches on the Screen====

----
=====CurrentTouch=====
======Examples======

{{{
#!lua
function draw()
    background( 0 )
    fill( 255, 0, 0 )
    ellipse( CurrentTouch.x, CurrentTouch.y, 300 )
end
}}}

======Description======


This global variable always represents the current single touch on the screen. It is a **touch** datatype, see the related items for more information.

======Syntax======

{{{
#!lua
CurrentTouch
}}}

======Related======

# [[Documentation#touch|touch]]

----
=====touch=====
======Description======


This type represents data about a single touch on the screen.

======Syntax======

{{{
#!lua
touch.id
touch.x
touch.y
touch.prevX
touch.prevY
touch.deltaX
touch.deltaY
touch.state
touch.tapCount
}}}

======Parameters======

|=Name|=Description|
|id|int, a unique identifier for this touch|
|x|float, specifies the x position of the touch on the screen|
|y|float, specifies the y position of the touch on the screen|
|prevX|float, specifies the x position, from the previous frame, of the touch on the screen|
|prevY|float, specifies the y position, from the previous frame, of the touch on the screen|
|deltaX|float, specifies the x delta since the last frame, the amount the touch has moved|
|deltaY|float, specifies the y delta since the last frame, the amount the touch has moved|
|state|the state of the touch, can be BEGAN, MOVING or ENDED|
|tapCount|how many times the touch has been tapped|

======Related======

# [[Documentation#currenttouch|CurrentTouch]]

----
===Parameters===
====Creating Parameters to Control Your Projects====

----
=====parameter( name, min, max )=====
======Examples======

{{{
#!lua
function setup()
    --Creates a global variable called Radius
    parameter("Radius", 50.0, 300.0, 100.0)
end

function draw()
    background(128)
    ellipseMode(RADIUS)
    ellipse(WIDTH/2, HEIGHT/2, Radius)
end
}}}

======Description======


This function creates a visual slider in the viewer that can be used to adjust a global variable in your code.

\\
You generally call the **parameter()** function in the **setup()** function of your **main** file. The string you specify for **name** will be exposed as a global variable that can be used in your code. When you adjust the slider in the viewer, the variable will be set appropriately. The last three parameters, **min**, **max** and **initial** allow you to set the minimum, maximum and initial value of your parameter respectively. If an initial value is not specified, then the parameter takes on the minimum value initially. If no minimum or maximum values are specified, the parameter uses the range [0, 1].



======Syntax======

{{{
#!lua
parameter( name )
parameter( name, min, max )
parameter( name, min, max, initial )
}}}

======Parameters======

|=Name|=Description|
|name|string, the parameter function will create a global variable with this name|
|min|int or float, specifies the minimum value that your parameter can take|
|max|int or float, specifies the maximum value that your parameter can take|
|initial|int or float, specifies the initial, or starting, value of the parameter|

======Related======

# [[Documentation#iparameter|iparameter]]

----
=====iparameter( name, min, max )=====
======Examples======

{{{
#!lua
function setup()
    --Creates a global variable called Radius
    parameter("Radius", 50, 300, 100)
end

function draw()
    background(128)
    ellipseMode(RADIUS)
    ellipse(WIDTH/2, HEIGHT/2, Radius)
end
}}}

======Description======


This function creates a visual slider in the viewer that can be used to adjust a global variable in your code.

\\
The main difference between this function and the **parameter()** function is that this function always sets the variable declared in **name** to an integer value. Thus its min, max and initial values must also be integers.

\\
You generally call the **iparameter()** function in the **setup()** function of your **main** file. The string you specify for **name** will be exposed as a global variable that can be used in your code. When you adjust the slider in the viewer, the variable will be set appropriately. The last three parameters, **min**, **max** and **initial** allow you to set the minimum, maximum and initial value of your parameter respectively. If an initial value is not specified, then the parameter takes on the minimum value initially. If no minimum or maximum values are specified, the parameter uses the range [0, 10].



======Syntax======

{{{
#!lua
iparameter( name )
iparameter( name, min, max )
iparameter( name, min, max, initial )
}}}

======Parameters======

|=Name|=Description|
|name|string, the parameter function will create a global variable with this name|
|min|int, specifies the minimum value that your parameter can take|
|max|int, specifies the maximum value that your parameter can take|
|initial|int, specifies the initial, or starting, value of the parameter|

======Related======

# [[Documentation#parameter|parameter]]

----
=====clearParameters()=====
======Description======


This function clears the parameter list of all parameter sliders and watch values. You can then re-add parameters using the **parameter()**, **iparameter()** and **watch()** functions.



======Syntax======

{{{
#!lua
clearParameters()
}}}

======Related======

# [[Documentation#parameter|parameter]]
# [[Documentation#iparameter|iparameter]]
# [[Documentation#watch|watch]]

----
=====clearOutput()=====
======Description======


This function clears the output buffer for the **print()** function.



======Syntax======

{{{
#!lua
clearOutput()
}}}


----
=====watch( name )=====
======Examples======

{{{
#!lua
function setup()
    --Shows the elapsed time in the viewer
    watch("ElapsedTime")
end
}}}

======Description======


This function allows you to monitor the value of a Lua expression within the viewer. Generally you call the **watch()** function from the **setup()** function in your **main** file.



======Syntax======

{{{
#!lua
watch( name )
}}}

======Parameters======

|=Name|=Description|
|name|string, the global variable to watch|


----
===Physics===
====Dynamic Motion with Forces, Joints and Collisions====

----
=====physics.body=====
======Examples======

{{{
#!lua
-- create a circle with 25px radius
circle = physics.body(CIRCLE, 25)
}}}

======Description======


This type represents a dynamic rigid body.

======Syntax======

{{{
#!lua
myBody = physics.body( CIRCLE, radius )

myBody = physics.body( POLYGON,
                       vec2(-10,10),
                       vec2(-10,-10),
                       vec2(10,-10),
                       vec2(10,10)

myBody = physics.body( CHAIN, loop,
                       vec2(0,0),
                       vec2(10,5),
                       vec2(15,10) )

myBody = physics.body( EDGE, vec2(0,0),
                       vec2(10,10) )
}}}

======Parameters======

|=Name|=Description|
|type|int, the type of the body, can be STATIC, DYNAMIC or KINEMATIC|
|shapeType|readonly, the shape type of the body, can be CIRCLE, POLYGON, CHAIN or EDGE|
|radius|float, the radius of the body, only valid for circle shape types|
|points|table, a table containing the point that make up the body, only valid for polygon shape types|
|x|float, the x position of the body in pixels|
|y|float, the y position of the body in pixels|
|position|vec2, the position of the body wrapped in a vector|
|angle|float, the angle of the body in degrees|
|linearVelocity|vec2, the current linear velocity of the body in pixels per second|
|angularVelocity|float, the angular velocity of the body in degrees per second|
|density|float, the density of the body in kg/m^2, 1 by default, cannot be negative|
|mass|float, the mass of the body in kg, cannot be negative. If you set this, density will be ignored|
|inertia|float, the momoment of inertia of the body. Cannot be set|
|restitution|float, the restitution, or 'bouncyness' of the body|
|friction|float, the friction of the body determines how easy the object slides|
|fixedRotation|boolean, locks the rotation of this body|
|active|boolean, set to false to remove from simulation|
|awake|boolean, true if body is currently awake, false otherwise|
|sleepingAllowed|boolean, set to false to prevent bodies from sleeping (default: true)|
|bullet|boolean, set to true for fast moving bodies to prevent tunneling|
|gravityScale|float, controls the influence of gravity on this body, 1 by default|
|interpolate|boolean, controls render interpolation, used to smooth out motion but introduces slight lag|
|info|value, used for storing arbitrary data in this body|

======Related======

# [[Documentation#physics.joint|physics.joint]]

----
=====CIRCLE=====
======Description======


This constant specifies the circle shape type.

Circle shapes are the fastest and simplest of the shape types, defined with a single parameter, **radius**.



======Syntax======

{{{
#!lua
CIRCLE
}}}

======Returns======


int

======Related======

# [[Documentation#physics.body|physics.body]]

----
=====POLYGON=====
======Description======


This constant specifies the polygon shape type.

Polygon shapes are defined by a series of vertices. Non convex polygons are automatically decomposed into a set of convex polygons.



======Syntax======

{{{
#!lua
POLYGON
}}}

======Returns======


int

======Related======

# [[Documentation#physics.body|physics.body]]

----
=====CHAIN=====
======Description======


This constant specifies the chain shape type.

Chain shapes are defined by a series of vertices that form an equivalent set of connected edges. This shape type has no mass and cannot be used in dynamic bodies.



======Syntax======

{{{
#!lua
CHAIN
}}}

======Returns======


int

======Related======

# [[Documentation#physics.body|physics.body]]

----
=====EDGE=====
======Description======


This constant specifies the edge shape type.

Edge shapes are defined by two vertices, which form a straight line. This shape type has no mass and cannot be used in dynamic bodies.



======Syntax======

{{{
#!lua
EDGE
}}}

======Returns======


int

======Related======

# [[Documentation#physics.body|physics.body]]

----
=====DYNAMIC=====
======Description======


This constant specifies the dynamic body type.

Dynamic bodies move under the influence of collisions, forces, joints and gravity.



======Syntax======

{{{
#!lua
DYNAMIC
}}}

======Returns======


int

======Related======

# [[Documentation#physics.body|physics.body]]

----
=====STATIC=====
======Description======


This constant specifies the static body type.

Static bodies are unaffected by forces and collisions. They also do not collide with other static or kinematic bodies.

Also note that you cannot attach two static/kinematic bodies together with a joint.



======Syntax======

{{{
#!lua
STATIC
}}}

======Returns======


int

======Related======

# [[Documentation#physics.body|physics.body]]

----
=====KINEMATIC=====
======Description======


This constant specifies the kinematic body type.

Kinematic bodies are unaffected by forces and collisions. Unlike static bodies, kinematic bodies are meant to be moved, usually by setting linear velocity directly. They also do not collide with other static or kinematic bodies.

Also note that you cannot attach two static/kinematic bodies together with a joint.



======Syntax======

{{{
#!lua
KINEMATIC
}}}

======Returns======


int

======Related======

# [[Documentation#physics.body|physics.body]]

----
=====physics.joint=====
======Description======


This type represents a joint that constrains two rigid bodies together.

======Syntax======

{{{
#!lua
physics.joint( REVOLUTE, bodyA, bodyB,
 anchor )
physics.joint( PRISMATIC, bodyA, bodyB,
 anchorA, anchorB )
physics.joint( DISTANCE, bodyA, bodyB,
 anchorA, anchorB )
physics.joint( WELD, bodyA, bodyB,
 anchor )
}}}

======Parameters======

|=Name|=Description|
|type|int, the type of the joint, can be REVOLUTE, DISTANCE, PRISMATIC or WELD|
|bodyA|body, the first body attached to this joint|
|bodyB|body, the second body attached to this joint|
|anchorA|vec2, the anchor for the first body in world coordinates|
|anchorB|vec2, the anchor for the second body in world coordinates|
|reactionForce|vec2, the current amount of force used by the joint to constrain the relative motion between the two bodies. This can be used to break joints when the force reaches a given threshold|
|reactionTorque|float, the current amount of torque used by the joint to constrain the relative rotation between the two bodies. This can be used to break joints when the torque reaches a given threshold|
|enableLimit|boolean, whether or not the limit for this joint is enabled. Only certain joints, such as REVOLUTE and PRISMATIC have limits|
|lowerLimit|float, the lower limit of this joint. For REVOLUTE joints this represents the angular limit between bodies in degrees. For PRISMATIC joints this represents the translation limit|
|upperLimit|float, the upper limit of this joint. For REVOLUTE joints this represents the angular limit between bodies in degrees. For PRISMATIC joints this represents the translation limit|
|enableMotor|boolean, whether or not the motor for this joint is enabled. Only certain joints, such as REVOLUTE and PRISMATIC have motors|
|motorSpeed|float, the desired speed of the motor. For REVOLUTE joints this is in degrees per second. For PRISMATIC joints this is specified in pixels per second|
|maxMotorTorque|float, the maximum amount of torque the motor can apply to reach the desired motor speed. Only REVOLUTE joints have this property|
|maxMotorForce|float, the maximum amount of force the motor can apply to reach the desired motor speed. Only PRISMATIC joints have this property|
|length|float, the length of the joint. Only applies to DISTANCE joints|
|frequency|float, The softness of the joint, set to zero for stiff joints. Only applies to DISTANCE and WELD joints|
|dampingRatio|float, Controls the damping of soft joints, higher values reduce oscillation, set to zero for stiff joints. Only applies to DISTANCE and WELD joints|

======Related======

# [[Documentation#physics.body|physics.body]]

----
=====REVOLUTE=====
======Description======


This constant specifies the revolute joint type.

Revolute joints constrain two bodies so that they rotate about a single anchor point.



======Syntax======

{{{
#!lua
REVOLUTE
}}}

======Returns======


int

======Related======

# [[Documentation#physics.joint|physics.joint]]

----
=====DISTANCE=====
======Description======


This constant specifies the distance joint type.

Distance joints constrain two bodies so that they maintain a fixed distance between their respective anchor points. The length of a distance joint is taken from the initial distance between the two anchor points in world space. Setting the frequency and damping ratio of the joint allows for soft spring-like behaviour.



======Syntax======

{{{
#!lua
DISTANCE
}}}

======Returns======


int

======Related======

# [[Documentation#physics.joint|physics.joint]]

----
=====PRISMATIC=====
======Description======


This constant specifies the prismatic joint type.

Prismatic joints constrain the motion of two bodies along the axis between the two specified anchor points. This allows for telescopic motion, while restricting relative rotation between the two bodies.



======Syntax======

{{{
#!lua
PRISMATIC
}}}

======Returns======


int

======Related======

# [[Documentation#physics.joint|physics.joint]]

----
=====WELD=====
======Description======


This constant specifies the weld joint type.

Weld joints constrain the motion and relative rotation between two bodies, effectively turning them into a single body. Due to the iterative nature of the solver, weld joints can bend when put under stress and may fail completely when large forces are involved or several weld joints are chained together to form a larger object.



======Syntax======

{{{
#!lua
WELD
}}}

======Returns======


int

======Related======

# [[Documentation#physics.joint|physics.joint]]

----
=====Contacts Overview=====
======Description======


A contact occurs whenever two bodies collide with each other. Codea allows you to handle contacts by implementing a global function called **collide( contact )** in your code.

\\

{{{
#!lua
-- This gets called whenever two bodies collide
function collide( contact )
    if contact.state == BEGAN then
        print("HIT!")
    end
end
}}}


\\
Contact objects contain information about the collision, such as the state, position of the collision, which bodies were involved, and so on. For a full listing of data available in a contact, see the **physics.contact** documentation.



======Related======

# [[Documentation#physics.contact|physics.contact]]

----
=====physics.contact=====
======Examples======

{{{
#!lua
function collide(contact)
    if contact.state == BEGAN
        then print("HIT!")
    end
end
}}}

======Description======


This type represents a collision between two bodies.

\\
A **physics.contact** object is supplied to the global function **collide( contact )** whenever a two bodies collide, maintain contact over multiple frames, or separate from each other. The contact supplied by this event will remain static as it is only a copy of the underlying physical state.

======Syntax======

{{{
#!lua

}}}

======Parameters======

|=Name|=Description|
|id|number, a unique id that represents this contact|
|state|int, the current state of this contact, can be BEGAN, PERSIST, ENDED|
|touching|bool, whether or not the contact is currently touching. Due to the way contacts are cached this can be false under some circumstances.|
|position|vec2, the current position of this contact|
|normal|vec2, the current normal of this contact|
|normalImpulse|float, the magnitude of energy used to separate the two colliding bodies projected along the normal vector. Useful for measuring the strength of an impact|
|normalImpulse|float, the magnitude of energy used to separate the two colliding bodies projected along the tangent vector (perpendicular to the normal). Useful for measuring the friction of an impact|
|pointCount|int, the number of points in the contact manifold|
|points|table, an array of vec2's describing the contact manifold|
|bodyA|body, the first body in the collision represented by this contact|
|bodyB|body, the second body in the collision represented by this contact|

======Related======

# [[Documentation#physics.body|physics.body]]
# [[Documentation#physics.joint|physics.joint]]

----
=====body.applyForce( force )=====
======Description======


Applies a force to this body object.



======Syntax======

{{{
#!lua
myBody:applyForce( force )
myBody:applyForce( force, worldPoint )
}}}

======Parameters======

|=Name|=Description|
|force|vec2, the amount of force to apply as a vector|
|worldPoint|vec2, the point to apply the force from, in world coordinates|

======Related======

# [[Documentation#physics.body|physics.body]]
# [[Documentation#body.applytorque|body.applyTorque]]

----
=====body.applyTorque( torque )=====
======Description======


Applies torque to this body object.



======Syntax======

{{{
#!lua
myBody:applyTorque( applyTorque )
}}}

======Parameters======

|=Name|=Description|
|torque|float, the amount of torque|

======Related======

# [[Documentation#physics.body|physics.body]]
# [[Documentation#body.applyforce|body.applyForce]]

----
=====body.destroy()=====
======Examples======

{{{
#!lua
-- destroy should be used before
-- setting a body to nil
circle = physics.body(CIRCLE, 100)
circle:destroy()
circle = nil
}}}

======Description======


A body will be removed from the simulation automatically when garbage collected, however this may not happen immediately. To ensure that a body is removed from the simulation, use destroy(). Please note that all methods and properties will cease to work after destroy() is called.



======Syntax======

{{{
#!lua
myBody:destroy()
}}}

======Related======

# [[Documentation#physics.body|physics.body]]
# [[Documentation#body.applyforce|body.applyForce]]
# [[Documentation#body.destroy|body.destroy]]

----
=====body.testPoint( worldPoint )=====
======Examples======

{{{
#!lua
-- test if CurrentTouch is inside this body
circle = physics.body(CIRCLE, 100)
point = vec2(CurrentTouch.x, CurrentTouch.y)
if circle:testPoint(point) then print("HIT!") end
}}}

======Description======


Tests if worldPoint is inside this **body**.



======Syntax======

{{{
#!lua
testPoint( worldPoint )
}}}

======Parameters======

|=Name|=Description|
|worldPoint|vec2, the point to test for intersection, in world space|

======Returns======


true if worldPoint is inside this **body**, false otherwise

======Related======

# [[Documentation#physics.body|physics.body]]
# [[Documentation#body.applyforce|body.applyForce]]
# [[Documentation#body.destroy|body.destroy]]
# [[Documentation#body.testpoint|body.testPoint]]

----
=====body.testOverlap( otherBody )=====
======Examples======

{{{
#!lua
-- test if two bodies overlap
circle1 = physics.body(CIRCLE, 100)
circle2 = physics.body(CIRCLE, 10)

if circle1:testOverlap(circle2)
    then print("HIT!")
end
}}}

======Description======


Tests if this **body** intersects with **otherBody**.

This is useful if you want to do simple shape intersection tests that do not require realtime contact information.



======Syntax======

{{{
#!lua
testOverlap( otherBody )
}}}

======Parameters======

|=Name|=Description|
|otherBody|body, the body to test for intersection with|

======Returns======


true if this **body** is intersecting with **otherBody**, false otherwise

======Related======

# [[Documentation#physics.body|physics.body]]
# [[Documentation#body.applyforce|body.applyForce]]
# [[Documentation#body.destroy|body.destroy]]
# [[Documentation#body.testpoint|body.testPoint]]

----
=====body.getLocalPoint( worldPoint )=====
======Examples======

{{{
#!lua
-- TODO example
}}}

======Description======


Converts a point to the local coordinate space of this **body**



======Syntax======

{{{
#!lua
myBody:getLocalPoint( worldPoint )
}}}

======Returns======


vec2, coordinate in local space of this **body**

======Related======

# [[Documentation#physics.body|physics.body]]
# [[Documentation#body.applyforce|body.applyForce]]
# [[Documentation#body.destroy|body.destroy]]
# [[Documentation#body.testpoint|body.testPoint]]

----
=====body.getWorldPoint( localPoint )=====
======Examples======

{{{
#!lua
-- TODO example
}}}

======Description======


Converts a point from the local coordinate space of this **body** to world space



======Syntax======

{{{
#!lua
myBody:getWorldPoint( localPoint )
}}}

======Returns======


vec2, coordinate in world space

======Related======

# [[Documentation#physics.body|physics.body]]
# [[Documentation#body.applyforce|body.applyForce]]
# [[Documentation#body.destroy|body.destroy]]
# [[Documentation#body.testpoint|body.testPoint]]

----
=====body.getLinearVelocityFromWorldPoint( point )=====
======Examples======

{{{
#!lua
-- TODO example
}}}

======Description======


Samples the linear velocity of this **body** at a given point in world space.



======Syntax======

{{{
#!lua
myBody:getLinearVelocityFromWorldPoint( worldPoint )
}}}

======Returns======


vec2, linear velocity at worldPoint of this **body**

======Related======

# [[Documentation#physics.body|physics.body]]
# [[Documentation#body.applyforce|body.applyForce]]
# [[Documentation#body.destroy|body.destroy]]
# [[Documentation#body.testpoint|body.testPoint]]

----
=====body.getLinearVelocityFromLocalPoint( point )=====
======Examples======

{{{
#!lua
-- TODO example
}}}

======Description======


Samples the linear velocity of this **body** at a given point in local space.



======Syntax======

{{{
#!lua
myBody:getLinearVelocityFromLocalPoint( worldPoint )
}}}

======Returns======


vec2, linear velocity at localPoint of this **body**

======Related======

# [[Documentation#physics.body|physics.body]]
# [[Documentation#body.applyforce|body.applyForce]]
# [[Documentation#body.destroy|body.destroy]]
# [[Documentation#body.testpoint|body.testPoint]]

----
=====physics.pause()=====
======Description======


Pauses the physics simulation.



======Syntax======

{{{
#!lua
-- pause physics
physics.pause()
}}}

======Related======

# [[Documentation#physics.resume|physics.resume]]

----
=====physics.resume()=====
======Description======


Resumes the physics simulation.



======Syntax======

{{{
#!lua
-- resume physics
physics.resume()
}}}

======Related======

# [[Documentation#physics.pause|physics.pause]]

----
=====physics.raycast( start, end, ... )=====
======Description======


Performs a raycast from the **start** point to the **end** point.

Any additional parameters are treated as category filters, allowing certain bodies to be ignored. This function only returns hit information on the closest rigid body detected.



======Syntax======

{{{
#!lua
physics.raycast(start, end)
physics.raycast(start, end, category1)
physics.raycast(start, end, category1, category2)
}}}

======Parameters======

|=Name|=Description|
|start|vec2, the start point of the ray (technically a line segment, but finite for practical purposes)|
|end|vec2, the end point of the ray|

======Returns======


table, if the raycast intersects a body this function will return a table containing the following key-value pairs

body => detected body

point => point of intersection

normal => normal on surface of hit body

fraction => fraction of total ray length from start to intersecton point



======Related======

# [[Documentation#physics.raycastall|physics.raycastAll]]
# [[Documentation#physics.queryaabb|physics.queryAABB]]

----
=====physics.raycastAll( start, end, ... )=====
======Description======


Performs a raycast from the **start** point to the **end** point.

Any additional parameters are treated as category filters, allowing certain bodies to be ignored. This function returns an array of tables describing all objects hit along the ray, ordered from closest to farthest.



======Syntax======

{{{
#!lua
physics.raycastAll(start, end)
physics.raycastAll(start, end, category1)
physics.raycastAll(start, end, category1, category2)
}}}

======Parameters======

|=Name|=Description|
|start|vec2, the start point of the ray (technically a line segment, but finite for practical purposes)|
|end|vec2, the end point of the ray|

======Returns======


array, if the raycast intersects one or more bodies this function will an array of tables containing the following key-value pairs

body => detected body

point => point of intersection

normal => normal on surface of hit body

fraction => fraction of total ray length from start to intersecton point



======Related======

# [[Documentation#physics.raycast|physics.raycast]]
# [[Documentation#physics.queryaabb|physics.queryAABB]]

----
=====physics.queryAABB( lowerLeft, upperRight, ... )=====
======Description======


Performs a query to find all bodies within the supplied axis-aligned bounding box.

Any additional parameters are treated as category filters, allowing certain bodies to be ignored.



======Syntax======

{{{
#!lua
physics.queryAABB(lowerLeft, upperRight)

physics.queryAABB(lowerLeft, upperRight, category1)

physics.queryAABB(lowerLeft, upperRight,
                  category1, category2)
}}}

======Parameters======

|=Name|=Description|
|lowerLeft|vec2, the position of the lower left corner of the query axis-aligned bounding box|
|upperRight|vec2, the position of the upper right corner of the query axis-aligned bounding box|

======Returns======


array, returns all bodies that lie within the supplied bounding box

======Related======

# [[Documentation#physics.raycast|physics.raycast]]
# [[Documentation#physics.raycastall|physics.raycastAll]]
# [[Documentation#physics.queryaabb|physics.queryAABB]]

----
=====physics.gravity( x, y )=====
======Description======


Sets the gravity of the world, units are in pixels per second^2. Use the Gravity global to set to device gravity. When no parameters are passed, function returns current world gravity as a vec2.



======Syntax======

{{{
#!lua
physics.gravity( x, y )
physics.gravity( grav )
physics.gravity( Gravity )

}}}

======Parameters======

|=Name|=Description|
|x|float, gravity in the x-axis|
|y|float, gravity in the y-axis|
|grav|vec2, gravity in both axes|
|Gravity|vec3, device gravity used as a special case|

======Returns======


vec2, the current world gravity if no parameters are supplied

======Related======

# [[Documentation#physics.iterations|physics.iterations]]
# [[Documentation#physics.pixeltometerratio|physics.pixelToMeterRatio]]

----
=====physics.iterations( velIterations, posIterations )=====
======Description======


Sets the iterations used by the physics solver. Larger iterations tend to result in more stable physics, but will slow down the simulation.



======Syntax======

{{{
#!lua
physics.iterations( velocityIterations,
                    positionIterations )
}}}

======Parameters======

|=Name|=Description|
|velocityIterations|int, the number of velocity iterations performed each time step (default: 10)|
|positionIterations|int, the number of position iterations performed each time step (default: 8)|

======Related======

# [[Documentation#physics.gravity|physics.gravity]]
# [[Documentation#physics.pixeltometerratio|physics.pixelToMeterRatio]]

----
=====physics.pixelToMeterRatio( ptmRatio )=====
======Description======


Sets the ratio between pixels and meters in the simulation.

This is used to make objects on the screen appear at a reasonable scale, while allowing the physics engine to remain stable. The default value is 32, meaning that for every 32 pixels in screen space there is 1 meter in physics space. This can be largely ignored in most cases, however if dealing with objects much larger or smaller than the default settings, it can be useful to change the ratio to something closer to that scale. Passing no parameters will cause this function to return the current ratio.



======Syntax======

{{{
#!lua
physics.pixelToMeterRatio( ptmRatio )
physics.pixelToMeterRatio()
}}}

======Parameters======

|=Name|=Description|
|ptmRatio|int, the number of pixels per meter (default: 32)|

======Returns======


int, the current ratio (when no parameters are supplied)

======Related======

# [[Documentation#physics.gravity|physics.gravity]]
# [[Documentation#physics.iterations|physics.iterations]]

----
===Sounds===
====Playing and Generating Sound Effects====

----
=====sound( name, seed )=====
======Examples======

{{{
#!lua
-- using a string
sound( "jump", 1234 )
}}}


{{{
#!lua
-- using the predefined constant
sound( SOUND_JUMP, 1234 )
}}}


{{{
#!lua
-- using the table to define properties
sound( { Waveform = SOUND_NOISE,
         AttackTime = 1.2,
         SustainTime = 1 } )
}}}

======Description======


Calling this function immediately plays either a randomly generated sound with a type specified by **name** or using the given parameters.

\\
**sound()** uses sfxr to randomly generate sounds of a given type. The **name** parameter is a string specifying the type of sound (see related items), and the **seed** parameter allows you to choose a particular random sound. Sounds with the same name and seed always sound the same. If no **seed** is specified the resulting sound will be a random sound of the specified type. If a parameter_table is passed in, those values are used to generate the sound.



======Syntax======

{{{
#!lua
sound( name )
sound( name, seed )
sound( parameter_table )
sound( buffer )
}}}

======Parameters======

|=Name|=Description|
|name|string, the type of sound to play\\
can be "blit", "explode", "hit", "jump", "pickup", "powerup", "random" or "shoot". Can also be "data" followed by a base64 string encoding the parameters which is generated by Codea based on the sound picker panel properties and should not be edited|
|seed|int, specifies the random seed to use when generating a sound of this type|
|buffer|soundbuffer, specifies the raw sound data to play|
|parameter_table|table, specifies the parameters to use when generating a sound. This is an advanced option, the parameters will change the noise in subtle ways. Play with the Sounds Plus example app to see what these parameters do. Any missing keys will cause the sound to use a default value for that parameter\\
The table can contain the following (case sensitive) keys:\\
Waveform - The synthesizer waveform to use, can be SOUND_NOISE, SOUND_SAWTOOTH, SOUND_SINEWAVE, or SOUND_SQUAREWAVE\\
AttackTime - number\\
SustainTime - number\\
SustainPunch - number\\
DecayTime - number\\
StartFrequency - number\\
MinimumFrequency - number\\
Slide - number\\
DeltaSlide - number\\
VibratoDepth - number\\
VibratoSpeed - number\\
ChangeAmount - number\\
ChangeSpeed - number\\
SquareDuty - number\\
DutySweep - number\\
RepeatSpeed - number\\
PhaserSweep - number\\
LowPassFilterCutoff - number\\
LowPassFilterCutoffSweep - number\\
LowPassFilterResonance - number\\
HighPassFilterCutoff - number\\
HighPassFilterCutoffSweep - number\\
Volume - number\\
|

======Related======

# [[Documentation#sound_blit|SOUND_BLIT]]
# [[Documentation#sound_explode|SOUND_EXPLODE]]
# [[Documentation#sound_hit|SOUND_HIT]]
# [[Documentation#sound_jump|SOUND_JUMP]]
# [[Documentation#sound_pickup|SOUND_PICKUP]]
# [[Documentation#sound_powerup|SOUND_POWERUP]]
# [[Documentation#sound_random|SOUND_RANDOM]]
# [[Documentation#sound_shoot|SOUND_SHOOT]]
# [[Documentation#sound_noise|SOUND_NOISE]]
# [[Documentation#sound-buffer|sound buffer]]
# [[Documentation#sound_squarewave|SOUND_SQUAREWAVE]]
# [[Documentation#sound_sinewave|SOUND_SINEWAVE]]
# [[Documentation#sound_sawtooth|SOUND_SAWTOOTH]]

----
=====soundbuffer( data, format, freq )=====
======Examples======

{{{
#!lua
-- Creating a sound buffer object
function setup()
    tap = false
    iparameter("freq",1,4000,800)
    parameter("length",0.1,1,0.5)
end

function makeBuffer()
    local data = ""
    datum="\0\255"
    numSamples = freq * length
    for i = 1,numSamples/#datum do
        data = data .. datum
    end

    return sound buffer( data, FORMAT_MONO8, freq )
end

function touched(touch)
    if touch.state == ENDED and
       touch.tapCount == 1 then
        tap = true
    end
end

function draw()
    background(0)
    if tap then
        b = makeBuffer()
        sound(b)
        tap = false
    end
end

}}}

======Description======


This object represents a sound buffer containing arbitrary audio data. You may create **soundbuffer** objects using **soundbuffer( data, format, freq )** where the data is uncompressed PCM audio and the format is one of FORMAT_MONO8, FORMAT_MONO16, FORMAT_STEREO8, or FORMAT_STEREO16.



======Syntax======

{{{
#!lua
soundbuffer( data, format, freq )
}}}

======Parameters======

|=Name|=Description|
|data|string, uncompressed audio data|
|format|FORMAT_MONO8, FORMAT_MONO16, FORMAT_STEREO8 or FORMAT_STEREO16|
|freq|integer, the frequency of the data|

======Returns======


A new soundbuffer object

======Related======

# [[Documentation#sound|sound]]

----
=====soundBufferSize( size )=====
======Examples======

{{{
#!lua
-- setting the sound buffer maximum size
soundBufferSize( 3 )
}}}


{{{
#!lua
-- reading the current maximum size and used size
maxSize, usedSize = nsoundBufferSize()
}}}


{{{
#!lua
-- setting to no limit
soundBufferSize(0)
}}}

======Description======


Calling this function will set the maximum buffer size for sounds. Sounds are stored in a buffer so that they do not need to be recreated if reused. Sounds are removed from this buffer on a least recently used basis when the buffer is full and a new sound is added. For example, if the buffer is 2 megabytes (the default), and we add a sound that puts it over the limit, the sound we used the longest time ago is removed from the buffer and will have to be re-created if played again. Generating the sound data can take a considerable amount of time for longer sounds.

Playing a sound at 0 volume counts as playing and can be used to keep a sound in the cache (and to pre-generate a sound in the setup function.)

Calling this method with 0 for the size sets the buffer to no limit. This can cause Codea to crash if too many sounds are generated as it may run out of memory.

Calling this with no parameters returns the max size and current size of the buffer.



======Syntax======

{{{
#!lua
soundBufferSize( size )
soundBufferSize()
}}}

======Parameters======

|=Name|=Description|
|size|number, the maximum size of the buffer in megabytes. This can be a fraction. If this is 0, the buffer size is unlimited. An unlimited buffer size can cause Codea to crash if it runs out of memory, so take care if it is used.|

======Returns======


If no parameters are given, a pair of values: maxBufferSize, currentBufferSize

======Related======

# [[Documentation#sound|sound]]

----
=====SOUND_JUMP=====
======Description======


This constant specifies a jump sound. Similar to a character jumping in a platform game.

======Syntax======

{{{
#!lua
SOUND_JUMP
}}}

======Returns======


The string "jump"

======Related======

# [[Documentation#sound|sound]]

----
=====SOUND_HIT=====
======Description======


This constant specifies a hit sound. For example, when the enemy collides with the player.

======Syntax======

{{{
#!lua
SOUND_HIT
}}}

======Returns======


The string "hit"

======Related======

# [[Documentation#sound|sound]]

----
=====SOUND_PICKUP=====
======Description======


This constant specifies a pickup sound. For example, collecting coins in a game.

======Syntax======

{{{
#!lua
SOUND_PICKUP
}}}

======Returns======


The string "pickup"

======Related======

# [[Documentation#sound|sound]]

----
=====SOUND_POWERUP=====
======Description======


This constant specifies a powerup sound. For example, collecting bonuses in a game.

======Syntax======

{{{
#!lua
SOUND_POWERUP
}}}

======Returns======


The string "powerup"

======Related======

# [[Documentation#sound|sound]]

----
=====SOUND_SHOOT=====
======Description======


This constant specifies a shooting sound. For example, firing a bullet in a game.

======Syntax======

{{{
#!lua
SOUND_SHOOT
}}}

======Returns======


The string "shoot"

======Related======

# [[Documentation#sound|sound]]

----
=====SOUND_EXPLODE=====
======Description======


This constant specifies an explosion sound. For example, a space ship blowing up.

======Syntax======

{{{
#!lua
SOUND_EXPLODE
}}}

======Returns======


The string "explode"

======Related======

# [[Documentation#sound|sound]]

----
=====SOUND_BLIT=====
======Description======


This constant specifies a generic "blit" sound.

======Syntax======

{{{
#!lua
SOUND_BLIT
}}}

======Returns======


The string "blit"

======Related======

# [[Documentation#sound|sound]]

----
=====SOUND_RANDOM=====
======Description======


This constant specifies a randomly generated sound. You can use this in conjunction with the seed value of the **sound()** function to find a sound that you like.

======Syntax======

{{{
#!lua
SOUND_RANDOM
}}}

======Returns======


The string "random"

======Related======

# [[Documentation#sound|sound]]

----
=====SOUND_NOISE=====
======Description======


This specifices to use a white noise function as the waveform for this sound

======Syntax======

{{{
#!lua
SOUND_NOISE
}}}

======Returns======


The integer 3

======Related======

# [[Documentation#sound|sound]]

----
=====SOUND_SAWTOOTH=====
======Description======


This specifices to use a sawtooth function as the waveform for this sound

======Syntax======

{{{
#!lua
SOUND_SAWTOOTH
}}}

======Returns======


The integer 1

======Related======

# [[Documentation#sound|sound]]

----
=====SOUND_SINEWAVE=====
======Description======


This specifices to use a sine wave function as the waveform for this sound

======Syntax======

{{{
#!lua
SOUND_SINEWAVE
}}}

======Returns======


The integer 2

======Related======

# [[Documentation#sound|sound]]

----
=====SOUND_SQUAREWAVE=====
======Description======


This specifices to use a square wave function as the waveform for this sound

======Syntax======

{{{
#!lua
SOUND_SQUAREWAVE
}}}

======Returns======


The integer 0

======Related======

# [[Documentation#sound|sound]]

----
===Display &amp; Keyboard===
====Using the Viewer's Display Modes====

----
=====displayMode( MODE )=====
======Examples======

{{{
#!lua
function setup()
    --Set the viewer to fullscreen
    displayMode( FULLSCREEN )
end
}}}


{{{
#!lua
function setup()
    --Set the viewer to standard
    --i.e. visible parameters and output
    displayMode( STANDARD )
end
}}}


{{{
#!lua
function setup()
    --Set the viewer to fullscreen
    --Hide back/pause/play buttons
    displayMode( FULLSCREEN_NO_BUTTONS )
end
}}}

======Description======


Changes the display mode of the viewer. You can use this to render your games and simulations in fullscreen mode, fullscreen mode without buttons, or standard mode

======Syntax======

{{{
#!lua
displayMode( STANDARD |
             FULLSCREEN |
             FULLSCREEN_NO_BUTTONS )
}}}

======Parameters======

|=Name|=Description|
|mode|Either STANDARD, FULLSCREEN or FULLSCREEN_NO_BUTTONS|

======Related======

# [[Documentation#standard|STANDARD]]
# [[Documentation#fullscreen|FULLSCREEN]]
# [[Documentation#fullscreen_no_buttons|FULLSCREEN_NO_BUTTONS]]

----
=====FULLSCREEN=====
======Description======


Use this value in **displayMode()** to set the viewer to fullscreen mode. The Back, Pause, Play and Reset buttons will still be visible in the lower left corner of the screen.

======Syntax======

{{{
#!lua
FULLSCREEN
}}}

======Related======

# [[Documentation#displaymode|displayMode]]

----
=====STANDARD=====
======Description======


Use this value in **displayMode()** or **backingMode()**

\\
When used with **displayMode()** this sets the viewer to standard screen mode. You will be able to see the output and parameters panes to the left of the viewer, and the Back, Pause, Play and Reset buttons will be visible in the lower left corner of the screen.

\\
When used with **backingMode()** this tells the viewer to render without using a retained backing, this means that the contents of the previous frame are not guaranteed to be preserved when entering the **draw()** call. This offers the best drawing performance.



======Syntax======

{{{
#!lua
displayMode( STANDARD )
backingMode( STANDARD )
}}}

======Related======

# [[Documentation#displaymode|displayMode]]
# [[Documentation#backingmode|backingMode]]

----
=====FULLSCREEN_NO_BUTTONS=====
======Description======


Use this value in **displayMode()** to set the viewer to fullscreen mode and hide //all// buttons on the screen. Note: you will not be able to exit the viewer unless you implement your own call to the **close()** function. You can force the standard Back button to appear by triple-tapping the screen with three fingers.

======Syntax======

{{{
#!lua
FULLSCREEN_NO_BUTTONS
}}}

======Related======

# [[Documentation#displaymode|displayMode]]
# [[Documentation#close|close]]

----
=====Orientation Overview=====
======Examples======

{{{
#!lua
supportedOrientations(ANY)

function setup()
    --Any orientation supported (default)
end

function orientationChanged( newOrientation )
    -- This function gets called when
    -- the device orientation changes
end
}}}

======Description======


Codea allows your projects to run in any orientation your device supports. However, you can limit supported orientations by using the **supportedOrientations()** function. You might want to do this if you only want your project to run in landscape mode, or if you want to make use of the accelerometer and do not want the user to inadvertently rotate the screen.

\\
When the device orientation changes, Codea calls the global function **orientationChanged( orientation )** and passes it the new orientation.



======Related======

# [[Documentation#supportedorientations|supportedOrientations]]
# [[Documentation#currentorientation|CurrentOrientation]]

----
=====CurrentOrientation=====
======Description======


This global contains the current orientation and can be one of the following: PORTRAIT, PORTRAIT_UPSIDE_DOWN, LANDSCAPE_LEFT, LANDSCAPE_RIGHT.



======Related======

# [[Documentation#portrait|PORTRAIT]]
# [[Documentation#portrait_upside_down|PORTRAIT_UPSIDE_DOWN]]
# [[Documentation#landscape_left|LANDSCAPE_LEFT]]
# [[Documentation#landscape_right|LANDSCAPE_RIGHT]]

----
=====supportedOrientations( ORIENTATION, ... )=====
======Examples======

{{{
#!lua
supportedOrientations(PORTRAIT_ANY)

function setup()
    --Only support portrait orientations
end
}}}


{{{
#!lua
supportedOrientations(LANDSCAPE_LEFT)

function setup()
    --Only support landscape left orientation
end
}}}

======Description======


Use this function to tell Codea which orientations the viewer should support for your project. This function accepts a variable number of arguments, each one specifying an orientation you wish to support. If you call this function with no arguments it will return all the currently supported orientations.

\\
Note that while you are allowed to call this function from within your **setup()** function, it is recommended that you call this function from //outside// your **setup()** function, as indicated by the above examples. This is because by the time **setup()** is executed the viewer has already assumed an orientation and will only lock into a new orientation once the device is rotated. If called in the global scope the viewer will be configured in advance to support the orientation(s) you desire.



======Syntax======

{{{
#!lua
supportedOrientations()
supportedOrientations( orient1, orient2, … )
}}}

======Parameters======

|=Name|=Description|
|orientation|Can be one of the following values:\\
ANY\\
PORTRAIT\\
PORTRAIT_UPSIDE_DOWN\\
PORTRAIT_ANY\\
LANDSCAPE_LEFT\\
LANDSCAPE_RIGHT\\
LANDSCAPE_ANY

|

======Returns======


All the currently supported orientations if called with no arguments. Otherwise this function returns nothing.

======Related======

# [[Documentation#any|ANY]]
# [[Documentation#portrait_any|PORTRAIT_ANY]]
# [[Documentation#portrait|PORTRAIT]]
# [[Documentation#portrait_upside_down|PORTRAIT_UPSIDE_DOWN]]
# [[Documentation#landscape_any|LANDSCAPE_ANY]]
# [[Documentation#landscape_left|LANDSCAPE_LEFT]]
# [[Documentation#landscape_right|LANDSCAPE_RIGHT]]

----
=====ANY=====
======Description======


Use this value in **supportedOrientation()** to allow the viewer to assume any orientation when the device is rotated.



======Syntax======

{{{
#!lua
supportedOrientation( ANY )
}}}

======Related======

# [[Documentation#supportedorientations|supportedOrientations]]

----
=====PORTRAIT_ANY=====
======Description======


Use this value in **supportedOrientation()** to allow the viewer to assume either of the two portrait orientations (PORTRAIT, PORTRAIT_UPSIDE_DOWN) when the device is rotated.



======Syntax======

{{{
#!lua
supportedOrientation( PORTRAIT_ANY )
}}}

======Related======

# [[Documentation#supportedorientations|supportedOrientations]]
# [[Documentation#portrait|PORTRAIT]]
# [[Documentation#portrait_upside_down|PORTRAIT_UPSIDE_DOWN]]

----
=====PORTRAIT=====
======Description======


Use this value in **supportedOrientation()** to allow the viewer to assume the standard portrait orientation (home button at the bottom).



======Syntax======

{{{
#!lua
supportedOrientation( PORTRAIT )
}}}

======Related======

# [[Documentation#supportedorientations|supportedOrientations]]
# [[Documentation#portrait_upside_down|PORTRAIT_UPSIDE_DOWN]]

----
=====PORTRAIT_UPSIDE_DOWN=====
======Description======


Use this value in **supportedOrientation()** to allow the viewer to assume an inverted portrait orientation (home button at the top).



======Syntax======

{{{
#!lua
supportedOrientation( PORTRAIT_UPSIDE_DOWN )
}}}

======Related======

# [[Documentation#supportedorientations|supportedOrientations]]
# [[Documentation#portrait|PORTRAIT]]

----
=====LANDSCAPE_ANY=====
======Description======


Use this value in **supportedOrientation()** to allow the viewer to assume either of the two landscape orientations (LANDSCAPE_LEFT, LANDSCAPE_RIGHT) when the device is rotated.



======Syntax======

{{{
#!lua
supportedOrientation( LANDSCAPE_ANY )
}}}

======Related======

# [[Documentation#supportedorientations|supportedOrientations]]
# [[Documentation#landscape_left|LANDSCAPE_LEFT]]
# [[Documentation#landscape_right|LANDSCAPE_RIGHT]]

----
=====LANDSCAPE_LEFT=====
======Description======


Use this value in **supportedOrientation()** to allow the viewer to assume the landscape left orientation (home button on left).



======Syntax======

{{{
#!lua
supportedOrientation( LANDSCAPE_LEFT )
}}}

======Related======

# [[Documentation#supportedorientations|supportedOrientations]]
# [[Documentation#landscape_right|LANDSCAPE_RIGHT]]

----
=====LANDSCAPE_RIGHT=====
======Description======


Use this value in **supportedOrientation()** to allow the viewer to assume the landscape right orientation (home button on right).



======Syntax======

{{{
#!lua
supportedOrientation( LANDSCAPE_RIGHT )
}}}

======Related======

# [[Documentation#supportedorientations|supportedOrientations]]
# [[Documentation#landscape_left|LANDSCAPE_LEFT]]

----
=====Using the Keyboard=====
======Description======


You can use the keyboard in Codea to receive text input in your projects. In order to begin receiving keyboard events, call the **showKeyboard()** function. This will show the on-screen keyboard, unless an external keyboard is present. When key presses are made Codea calls the global function **keyboard( key )**. You must implement this function to receive keyboard events.

\\

{{{
#!lua
function keyboard( key )
    print("Key pressed: '".. key .."'")
end
}}}


Alternatively you can read the current keyboard buffer by calling **keyboardBuffer()**. See the **keyboardBuffer()** documentation for an example.



======Related======

# [[Documentation#showkeyboard|showKeyboard]]
# [[Documentation#hidekeyboard|hideKeyboard]]
# [[Documentation#keyboardbuffer|keyboardBuffer]]

----
=====showKeyboard()=====
======Examples======

{{{
#!lua
function touched(touch)
    --Show keyboard when the screen is touched
    showKeyboard()
end
}}}

======Description======


This function enables keyboard input and displays the software keyboard if necessary. After calling **showKeyboard()**, keyboard events will be delivered to a global function **keyboard( key )**. The current keyboard buffer can be read with the **keyboardBuffer()** function.



======Syntax======

{{{
#!lua
showKeyboard()
}}}

======Related======

# [[Documentation#hidekeyboard|hideKeyboard]]
# [[Documentation#keyboardbuffer|keyboardBuffer]]

----
=====hideKeyboard()=====
======Description======


This function disables keyboard input and hides the software keyboard if necessary.



======Syntax======

{{{
#!lua
hideKeyboard()
}}}

======Related======

# [[Documentation#showkeyboard|showKeyboard]]
# [[Documentation#keyboardbuffer|keyboardBuffer]]

----
=====keyboardBuffer()=====
======Examples======

{{{
#!lua
function touched(touch)
    --Show keyboard when the screen is touched
    showKeyboard()
end

function draw()
    background(40,40,50)
    fill(255)
    textMode(CORNER)
    buffer = keyboardBuffer()

    _,bufferHeight = textSize(buffer)
    if buffer then
        text( buffer, 10,
                         HEIGHT - 30 - bufferHeight )
    end
end
}}}

======Description======


This function reads the current keyboard buffer. Note that the keyboard buffer is cleared when the keyboard is shown.



======Syntax======

{{{
#!lua
buffer = keyboardBuffer()
}}}

======Returns======


Contents of keyboard buffer as a string

======Related======

# [[Documentation#showkeyboard|showKeyboard]]
# [[Documentation#hidekeyboard|hideKeyboard]]

----
=====BACKSPACE=====
======Examples======

{{{
#!lua
function keyboard(key)
    -- Did the user press backspace?
    if key == BACKSPACE then
        -- Do something
    end
end
}}}

======Description======


You can use this to check whether the key delivered to the global **keyboard( key )** function was the backspace key..



======Syntax======

{{{
#!lua
BACKSPACE
}}}

======Related======

# [[Documentation#keyboardoverview|keyboardOverview]]
# [[Documentation#showkeyboard|showKeyboard]]

----
=====startRecording()=====
======Description======


This function initiates the video recording feature of Codea. To stop video recording use the **stopRecording()** function. This function is identical to pressing the video record button in the viewer interface. Do not call this function in your **setup()** function.



======Syntax======

{{{
#!lua
startRecording()
}}}

======Related======

# [[Documentation#stoprecording|stopRecording]]
# [[Documentation#isrecording|isRecording]]

----
=====stopRecording()=====
======Description======


Use this function to stop Codea's video recording feature and save the recorded video to the device's camera roll.



======Syntax======

{{{
#!lua
stopRecording()
}}}

======Related======

# [[Documentation#startrecording|startRecording]]
# [[Documentation#isrecording|isRecording]]

----
=====isRecording()=====
======Description======


Use this function to programatically determine whether Codea is currently recording the screen.



======Syntax======

{{{
#!lua
isRecording()
}}}

======Returns======


Boolean, whether Codea is recording the screen

======Related======

# [[Documentation#startrecording|startRecording]]
# [[Documentation#stoprecording|stopRecording]]

----
=====backingMode( MODE )=====
======Examples======

{{{
#!lua
function setup()
    --Use a standard backing mode (default)
    backingMode( STANDARD )
end
}}}


{{{
#!lua
function setup()
    --Use a retained backing mode
    backingMode( RETAINED )
end
}}}

======Description======


Changes the backing mode of the viewer. The default, **STANDARD**, is the fastest drawing mode and **may not preserve** the contents of the previously drawn frame when setting up next frame.

Use the **RETAINED** backing mode to force the viewer to copy the contents of the previous frame into the current frame each time **draw()** is called. This is useful for projects that need to paint onto the screen and preserve the screen's contents, for example, painting or drawing applications.



======Syntax======

{{{
#!lua
backingMode( STANDARD|RETAINED )
}}}

======Parameters======

|=Name|=Description|
|mode|Either STANDARD or RETAINED|

======Related======

# [[Documentation#standard|STANDARD]]
# [[Documentation#retained|RETAINED]]

----
=====RETAINED=====
======Description======


Use this value in **backingMode()** to set the viewer to draw with a retained backing mode. This forces the viewer to copy the contents of the previous frame into the current frame each time **draw()** is called. This is useful for projects that need to paint onto the screen and preserve the screen's contents, for example, painting or drawing applications.



======Syntax======

{{{
#!lua
backingMode( RETAINED )
}}}

======Related======

# [[Documentation#backingmode|backingMode]]
# [[Documentation#standard|STANDARD]]

----
=====close()=====
======Examples======

{{{
#!lua
function touched(touch)
    --Exit if user taps
    if touch.tapCount == 1 and touch.state == ENDED then
        close()
    end
end
}}}

======Description======


Closes the viewer and returns to the editor. Calling **close()** is functionally the same as pressing the on-screen Back button. This function is useful if you are using **displayMode()** with the **FULLSCREEN_NO_BUTTONS** mode

======Syntax======

{{{
#!lua
close()
}}}

======Related======

# [[Documentation#displaymode|displayMode]]
# [[Documentation#fullscreen_no_buttons|FULLSCREEN_NO_BUTTONS]]

----
===Vector===
====Vector and Matrix Types====

----
=====vec2=====
======Examples======

{{{
#!lua
--Some vector operations
v1 = vec2( 1, 1 )
v2 = vec2( 4, 2 )

--Angle between
v1:angleBetween( v2 )

--Adding
v3 = v1 + v2

--Multiplying
v4 = v1 * 5.0

--Rotating by 45 degrees
v5 = v1:rotate(math.rad(45))
}}}

======Description======


This type represents a 2D vector. Most mathematical operators such as equality, addition, subtraction, multiplication and division are provided, so you can use **vec2** data types similarly to how you use numerical types. In addition there are a number of methods, such as **v:dot( vec2 )** that can be called on vec2 types, please see the related items below.

======Syntax======

{{{
#!lua
vec2.x
vec2.y
myVec = vec2( 2.5, 10.0 )

-- Supports operators:
--   v = vec2 + vec2
--   v = vec2 - vec2
--   v = vec2 * scalar
--   v = vec2 / scalar
--   v = -vec2
--   b = vec2 == vec2
--   print( vec2 )
}}}

======Parameters======

|=Name|=Description|
|x|float, the x component of this vec2|
|y|float, the y component of this vec2|

======Related======

# [[Documentation#vec2.dot|vec2.dot]]
# [[Documentation#vec2.normalize|vec2.normalize]]
# [[Documentation#vec2.dist|vec2.dist]]
# [[Documentation#vec2.distsqr|vec2.distSqr]]
# [[Documentation#vec2.len|vec2.len]]
# [[Documentation#vec2.lensqr|vec2.lenSqr]]
# [[Documentation#vec2.cross|vec2.cross]]
# [[Documentation#vec2.rotate|vec2.rotate]]
# [[Documentation#vec2.rotate90|vec2.rotate90]]
# [[Documentation#vec2.anglebetween|vec2.angleBetween]]

----
=====vec2.dot( v )=====
======Description======


This method returns the scalar dot product between two **vec2** types

======Syntax======

{{{
#!lua
v1 = vec2( 1, 1 )
x = v1:dot( v )
}}}

======Parameters======

|=Name|=Description|
|v|compute the dot product with this vec2 and v|

======Returns======


Dot product between this **vec2** and **v**

======Related======

# [[Documentation#vec2|vec2]]

----
=====vec2.normalize()=====
======Description======


This method returns a normalized version of the vector

======Syntax======

{{{
#!lua
v1 = vec2( 5, 5 )
v1 = v1:normalize()
}}}

======Returns======


Normalized version of this **vec2**

======Related======

# [[Documentation#vec2|vec2]]

----
=====vec2.dist( v )=====
======Description======


This method returns the distance between two **vec2** types

======Syntax======

{{{
#!lua
v1 = vec2( 1, 1 )
x = v1:dist( vec2(2, 2) )
}}}

======Parameters======

|=Name|=Description|
|v|compute the distance between this vec2 and v|

======Returns======


Distance between this **vec2** and **v**

======Related======

# [[Documentation#vec2|vec2]]

----
=====vec2.distSqr( v )=====
======Description======


This method returns the squared distance between two **vec2** types

======Syntax======

{{{
#!lua
v1 = vec2( 1, 1 )
x = v1:distSqr( vec2(2, 2) )
}}}

======Parameters======

|=Name|=Description|
|v|compute the squared distance between this vec2 and v|

======Returns======


Squared distance between this **vec2** and **v**

======Related======

# [[Documentation#vec2|vec2]]

----
=====vec2.len()=====
======Description======


This method returns the length of a **vec2**

======Syntax======

{{{
#!lua
v1 = vec2( 2, 1 )
x = v1:len()
}}}

======Returns======


Length of this **vec2**

======Related======

# [[Documentation#vec2|vec2]]

----
=====vec2.lenSqr()=====
======Description======


This method returns the squared length of a **vec2**

======Syntax======

{{{
#!lua
v1 = vec2( 2, 1 )
x = v1:lenSqr()
}}}

======Returns======


Squared length of this **vec2**

======Related======

# [[Documentation#vec2|vec2]]

----
=====vec2.cross( v )=====
======Description======


This method returns the cross product between two **vec2** types

======Syntax======

{{{
#!lua
v1 = vec2( 1, 1 )
v2 = v1:cross( vec2(2, 2) )
}}}

======Parameters======

|=Name|=Description|
|v|compute the cross product of this vec2 and v|

======Returns======


Cross product of this **vec2** and **v**

======Related======

# [[Documentation#vec2|vec2]]

----
=====vec2.rotate( angle )=====
======Description======


This method returns a rotated copy of a **vec2** type. The **angle** is assumed to be radians.

======Syntax======

{{{
#!lua
v1 = vec2( 1, 1 )
v1 = v1:rotate( math.rad(45) )
}}}

======Parameters======

|=Name|=Description|
|angle|float, rotate this vector by **angle** in radians|

======Returns======


Rotated version of this **vec2**

======Related======

# [[Documentation#vec2|vec2]]

----
=====vec2.rotate90()=====
======Description======


This method returns a copy of a **vec2** type, rotated 90 degrees.

======Syntax======

{{{
#!lua
v1 = vec2( 1, 1 )
v1 = v1:rotate90()
}}}

======Returns======


Rotated version of this **vec2**

======Related======

# [[Documentation#vec2|vec2]]

----
=====vec2.angleBetween( v )=====
======Description======


This method returns the angle between this **vec2** and **v** in radians.

======Syntax======

{{{
#!lua
v1 = vec2( 1, 1 )
angle = math.deg( v1:angleBetween( vec2(5, 2) ) )
}}}

======Parameters======

|=Name|=Description|
|v|compute the angle between this **vec2** and **v**|

======Returns======


Angle between **vec2** and **v** in radians

======Related======

# [[Documentation#vec2|vec2]]

----
=====vec3=====
======Description======


This type represents a 3D vector. Most mathematical operators such as equality, addition, subtraction, multiplication and division are provided, so you can use **vec3** data as you would normally use numerical types. In addition there are a number of methods, such as **v:dot( vec3 )** that can be called on vec3 types, please see the related items below.

======Syntax======

{{{
#!lua
vec3.x
vec3.y
vec3.z
myVec = vec3( 1.0, 2.0, 3.0 )
v = vec3(1,2,3) + vec3(3,2,1)
v = vec3(1,1,1) * 5
}}}

======Parameters======

|=Name|=Description|
|x|float, x dimension of this vector|
|y|float, y dimension of this vector|
|z|float, z dimension of this vector|

======Related======

# [[Documentation#vec3.dot|vec3.dot]]
# [[Documentation#vec3.normalize|vec3.normalize]]
# [[Documentation#vec3.dist|vec3.dist]]
# [[Documentation#vec3.distsqr|vec3.distSqr]]
# [[Documentation#vec3.len|vec3.len]]
# [[Documentation#vec3.lensqr|vec3.lenSqr]]
# [[Documentation#vec3.cross|vec3.cross]]

----
=====vec3.dot( v )=====
======Description======


This method returns the scalar dot product between two **vec3** types

======Syntax======

{{{
#!lua
v1 = vec3( 1, 1, 1 )
x = v1:dot( v )
}}}

======Parameters======

|=Name|=Description|
|v|compute the dot product with this vec3 and v|

======Returns======


Dot product between this **vec3** and **v**

======Related======

# [[Documentation#vec3|vec3]]

----
=====vec3.normalize()=====
======Description======


This method returns a normalized version of the vector

======Syntax======

{{{
#!lua
v1 = vec3( 5, 5, 5 )
v1 = v1:normalize()
}}}

======Returns======


Normalized version of this **vec3**

======Related======

# [[Documentation#vec3|vec3]]

----
=====vec3.dist( v )=====
======Description======


This method returns the distance between two **vec3** types

======Syntax======

{{{
#!lua
v1 = vec3( 1, 1, 1 )
x = v1:dist( vec3(2, 2, 2) )
}}}

======Parameters======

|=Name|=Description|
|v|compute the distance between this vec3 and v|

======Returns======


Distance between this **vec3** and **v**

======Related======

# [[Documentation#vec3|vec3]]

----
=====vec3.distSqr( v )=====
======Description======


This method returns the squared distance between two **vec3** types

======Syntax======

{{{
#!lua
v1 = vec3( 1, 1, 1 )
x = v1:distSqr( vec3(2, 2, 2) )
}}}

======Parameters======

|=Name|=Description|
|v|compute the squared distance between this vec3 and v|

======Returns======


Squared distance between this **vec3** and **v**

======Related======

# [[Documentation#vec3|vec3]]

----
=====vec3.len()=====
======Description======


This method returns the length of a **vec3**

======Syntax======

{{{
#!lua
v1 = vec3( 2, 1, 0 )
x = v1:len()
}}}

======Returns======


Length of this **vec3**

======Related======

# [[Documentation#vec3|vec3]]

----
=====vec3.lenSqr()=====
======Description======


This method returns the squared length of a **vec3**

======Syntax======

{{{
#!lua
v1 = vec3( 2, 1, 0 )
x = v1:lenSqr()
}}}

======Returns======


Squared length of this **vec3**

======Related======

# [[Documentation#vec3|vec3]]

----
=====vec3.cross( v )=====
======Description======


This method returns the cross product between two **vec3** types

======Syntax======

{{{
#!lua
v1 = vec3( 1, 1 )
v2 = v1:cross( vec3(2, 2) )
}}}

======Parameters======

|=Name|=Description|
|v|compute the cross product of this vec3 and v|

======Returns======


Cross product of this **vec3** and **v**

======Related======

# [[Documentation#vec3|vec3]]

----
=====matrix=====
======Examples======

{{{
#!lua
matrix[x] = y
m1 = matrix( 1,2,3,…,16 )
m2 = matrix( 4,5,6,…,20)

-- Supports operators:
m = m1 + m2
m = m1 - m2
m = m1 * 10
m = m1 / 10
m = -m1
checkEqual = m1 == m2
print( m1 )
}}}

======Description======


This type represents a 4x4 column-major matrix. This matrix type is used to represent transformations in Codea, and can be used with functions such as **modelMatrix()** and **viewMatrix()**. The matrix type supports the following arithmetic operators: multiplication (between two matrices), multiplication by scalar, division by scalar, equality, and element-wise addition and subtraction.

\\
Because this type is used to represent transformations it also provides a number of 3D transformation methods such as **matrix:translate(x,y,z)**, **matrix:rotate(angle,x,y,z)**. See the related items for a full list.

\\
Constructing a matrix with no parameters returns the identity matrix. Passing 16 numbers when constructing a matrix will assign those values to the elements of the matrix. Individual matrix elements can be accessed by their index, for example **m[1]** for the first element and **m[16]** for the last element. Entries are defined such that the x,y,z translation components are stored in elements 13, 14, and 15 respectively.



======Syntax======

{{{
#!lua
matrix[1] … matrix[16]
m = matrix()
m = matrix(1, 2, 3, …. 16)
m = matrix1 * matrix2
}}}

======Parameters======

|=Name|=Description|
|element|float, an element of the matrix|

======Returns======


A new matrix with the given elements

======Related======

# [[Documentation#modelmatrix|modelMatrix]]
# [[Documentation#matrix.rotate|matrix.rotate]]
# [[Documentation#matrix.translate|matrix.translate]]
# [[Documentation#matrix.scale|matrix.scale]]
# [[Documentation#matrix.inverse|matrix.inverse]]
# [[Documentation#matrix.transpose|matrix.transpose]]
# [[Documentation#matrix.determinant|matrix.determinant]]

----
=====matrix.rotate( m, r, x, y, z )=====
======Examples======

{{{
#!lua
m = matrix()
--Rotate about 0,0,1
rotated = m:rotate(30)

--Rotate by a given axis
rotated= m:rotate(30, 1, 0, 0)
}}}

======Description======


This method returns the matrix multiplied by a rotation matrix defining a rotation of angle degrees around the x,y,z axis or (0,0,1) if no axis is given.

======Syntax======

{{{
#!lua
rotated = m:rotate( angle, axisX, axisY, axisZ )
}}}

======Parameters======

|=Name|=Description|
|angle|float, the rotation in degrees|
|axisX|float, the x component of the axis of rotation|
|axisY|float, the y component of the axis of rotation|
|axisZ|float, the z component of the axis of rotation|

======Returns======


A matrix which rotates m by the specified rotation

======Related======

# [[Documentation#matrix|matrix]]

----
=====matrix.translate( m, x, y, z )=====
======Examples======

{{{
#!lua
m = matrix()
translated = m:translate(100,20,10)
}}}

======Description======


This method returns the matrix multiplied by a translation matrix defining a translation of x, y, z.

======Syntax======

{{{
#!lua
translated = m:translate( x, y, z )
}}}

======Parameters======

|=Name|=Description|
|x|float, the x component of translation|
|y|float, the y component of translation|
|z|float, optional, defaults to 0 – the z component of translation|

======Returns======


A matrix which translates m by the specified amount

======Related======

# [[Documentation#matrix|matrix]]

----
=====matrix.scale( m, x, y, z )=====
======Examples======

{{{
#!lua
m = matrix()
s = m:scale(100,20,10)

--Uniform scaling
s = m:scale(5)
}}}

======Description======


This method returns the matrix scaled by a translation matrix defining a scaling to each axis.

======Syntax======

{{{
#!lua
scaled = m:scale( x, y, z )
}}}

======Parameters======

|=Name|=Description|
|x|float, the x component of scale, or the uniform scale if no other components are given|
|y|float, optional, the y component of scale|
|z|float, optional, defaults to 1 if x and y are both given, otherwise x – the z component of scale|

======Returns======


A matrix which scales m by the specified amount

======Related======

# [[Documentation#matrix|matrix]]

----
=====matrix.inverse( m )=====
======Description======


This method returns the inverse of the given matrix, if such an inverse exists. If no inverse exists, the result is a matrix of NaN values. The inverse of a matrix is a matrix such that m * mInv = I, where I is the identity matrix.

======Syntax======

{{{
#!lua
inv = m:inverse()
}}}

======Parameters======

|=Name|=Description|
|m|the matrix to invert|

======Returns======


A matrix which inverts m

======Related======

# [[Documentation#matrix|matrix]]

----
=====matrix.transpose( m )=====
======Description======


This method returns the transpose of the given matrix. The transpose of a matrix is a matrix that is flipped on the major diagonal (ie, elements 1,6,11,16). For example element 2 and element 5 are swapped, etc.

======Syntax======

{{{
#!lua
transposed = m:transpose()
}}}

======Parameters======

|=Name|=Description|
|m|the matrix to transpose|

======Returns======


A matrix which is the transpose of m

======Related======

# [[Documentation#matrix|matrix]]

----
=====matrix.determinant( m )=====
======Description======


This method returns the determinant of the given matrix. This has various uses for determining characteristics of a matrix, especially whether it is invertible or not.

======Syntax======

{{{
#!lua
det = m:determinant()
}}}

======Returns======


A float equal to the determinant of m

======Related======

# [[Documentation#matrix|matrix]]

----
===Accelerometer===
====Detecting Device Motion and Gravity====

----
=====Gravity=====
======Description======


This global variable represents the current direction and amount of gravity relative to the screen orientation while the viewer is running. The y component of this vector will almost always be negative, indicating that the device is being held upright.



======Syntax======

{{{
#!lua
Gravity
Gravity.x
Gravity.y
Gravity.z
}}}

======Parameters======

|=Name|=Description|
|x|float, the amount of gravity in the x direction|
|y|float, the amount of gravity in the y direction|
|z|float, the amount of gravity in the z direction|

======Related======

# [[Documentation#vec3|vec3]]
# [[Documentation#useracceleration|UserAcceleration]]

----
=====UserAcceleration=====
======Description======


This global variable represents the current acceleration relative to the device while the viewer is running. You can use this to detect things such as shaking.



======Syntax======

{{{
#!lua
UserAcceleration
UserAcceleration.x
UserAcceleration.y
UserAcceleration.z
}}}

======Parameters======

|=Name|=Description|
|x|float, the amount of acceleration in the x direction|
|y|float, the amount of acceleration in the y direction|
|z|float, the amount of acceleration in the z direction|

======Related======

# [[Documentation#vec3|vec3]]
# [[Documentation#gravity|Gravity]]

----
===Network===
====Network Connections and Requests====

----
=====openURL( url )=====
======Examples======

{{{
#!lua
function touched(touch)
    openURL( 'http://twolivesleft.com' )
end

}}}

======Description======


This function opens the URL specified by **url** in an external browser.



======Syntax======

{{{
#!lua
openURL( url )
}}}

======Parameters======

|=Name|=Description|
|url|string, the url to open|


----
=====HTTP Callback Overview=====
======Description======


HTTP requests are handled by the **http.get** function. This function accepts a url (string) as its first argument, and a success and failure function as its second and third arguments respectively. The more advanced form of **http.get** accepts a table of parameters as its fourth argument.

\\

{{{
#!lua
-- Success function format
function success( response string or image,
                  statusCode,
                  responseHeaders )
}}}


\\

{{{
#!lua
-- Failure function format
function fail( error )
}}}




======Related======

# [[Documentation#http.get|http.get]]
# [[Documentation#image|image]]

----
=====http.get( url, successFunction )=====
======Examples======

{{{
#!lua
-- Downloading data
function setup()
    textData = nil

    -- Request some data
    http.get( 'http:twolivesleft.com/hello.txt',
              didGetData )
end

-- Our callback function
function didGetData( data, status, headers )
    print( status..' : '..data )
end


}}}


{{{
#!lua
-- Downloading an image
function setup()
    logoImage = nil

    -- Request some data
    http.get( 'http:twolivesleft.com/logo.png',
              didGetImage )
end

-- Our callback function
function didGetImage( theImage, status, head )
    logoImage = theImage
end

function draw()
    background(20,20,40)
    if logoImage ~= nil then
        sprite(logoImage, WIDTH/2,HEIGHT/2,WIDTH)
    end
end

}}}

======Description======


This function allows you to send a http request to the url specified by **url**. The request is asynchronous, so you must provide a **successFunction** to be called when the request succeeds. The success or fail function will be called outside of your draw function at some point in the future. You may also provide additional parameters, such as a failure function, and request type by using the more advanced **parameterTable** form of the function. For details on the structure of the callback functions, please see the HTTP Callback Overview in the related items, below.

\\
Note that the **successFunction** will be called if the request succeeds at all. This does not guarantee that the data was found. A 404 error will result in no data, but is an example of a successful request.

\\
**http.get** has special behaviour when it comes to images in PNG, JPEG and other formats. Rather than provide the raw data in the **successFunction** callback, Codea will automatically convert the data to an **image** type, which you can then draw to the screen immediately.



======Syntax======

{{{
#!lua
http.get( url, successFunction )
http.get( url, successFunction, failFunction )
http.get( url, success, fail, parameterTable )
}}}

======Parameters======

|=Name|=Description|
|url|string, the url to submit the request|
|successFunction|function, the function to be called when the request succeeds. This function will be called with an argument representing the returned data.|
|failFunction|function, the function to be called when the request fails. This function will be called with a string argument containing the error.|
|parameterTable|table, specifying advanced parameters\\

{{{
#!lua
"method" : "HEAD",\n           "GET",\n           "PUT",\n           "POST",\n           "DELETE"\n"headers" : table, string pairs\n           for name and value\n           of HTTP headers\n"data" : string, POST data.\n         Only used for POST\n         or PUT methods.\n"useragent" : string\n
}}}
|

======Related======

# [[Documentation#httpcallbackoverview|httpCallbackOverview]]
# [[Documentation#image|image]]

----
===Storage===
====Storing Persistent Data====

----
=====readImage( spriteKey )=====
======Examples======

{{{
#!lua
-- Read a sprite into an image
myImage = readImage('Planet Cute:Heart')
}}}

======Description======


This function reads a stored sprite (i.e., a sprite that is visible in the sprite picker) into an image type. You can read from the included sprite packs, or your Documents and Dropbox sprite packs.



======Syntax======

{{{
#!lua
readImage( spriteKey )
}}}

======Parameters======

|=Name|=Description|
|spriteKey|string, name of sprite pack and sprite, separated by a colon (e.g., "Documents:MySprite")|

======Returns======


The image associated with **spriteKey** or **nil** if **spriteKey** doesn't exist or is invalid.

======Related======

# [[Documentation#saveimage|saveImage]]
# [[Documentation#image|image]]

----
=====saveImage( spriteKey, image )=====
======Examples======

{{{
#!lua
-- Save a sprite into documents
function setup()
    myImage = image(400,400)

    setContext(myImage)
    background(0,0,0,0)
    fill(255,0,0)
    ellipse(200,200,200)
    setContext()

    saveImage('Documents:Circle', myImage)
end
}}}

======Description======


This function saves an image into a sprite pack. Only user sprite packs (**Documents** and **Dropbox**) are permitted for this operation. If an existing sprite exists under the **spriteKey** name it will be overwritten, if **nil** is specified for the **image** parameter then the sprite at **spriteKey** will be deleted.

\\
Note that if you are using a retina device, two files will be saved when using this function. A retina sized image with an "@2x" suffix, and a 50% scale non-retina image.

\\
Note that if you save an image to your **Dropbox** sprite pack then you will have to open the sprite picker and sync your Dropbox sprite pack in order for the image to be uploaded to your Dropbox account.



======Syntax======

{{{
#!lua
saveImage( spriteKey, image )
}}}

======Parameters======

|=Name|=Description|
|spriteKey|string, name of sprite pack and sprite, separated by a colon (e.g., "Documents:MySprite")|
|image|image, the image to be saved under **spriteKey**|

======Related======

# [[Documentation#readimage|readImage]]
# [[Documentation#image|image]]

----
=====readLocalData( key )=====
======Examples======

{{{
#!lua
-- Load high score
-- Defaults to 0 if it doesn't exist
highscore = readLocalData('highscore', 0)
}}}

======Description======


This function reads a value associated with **key** from the local device storage for the current project.

\\
Local storage for a particular project is unique to your device. That is, sharing your project will not share the associated data. This sort of storage is useful for things such as high scores, statistics, and any values you are likely to associate while a user is interacting with your game or simulation.



======Syntax======

{{{
#!lua
readLocalData( key )
readLocalData( key, defaultValue )
}}}

======Parameters======

|=Name|=Description|
|key|string, name of the piece of data you would like to get|
|defaultValue|if the key doesn't exist, this value is returned instead|

======Returns======


The value associated with **key**, or **defaultValue** if key doesn't exist and **defaultValue** is specified. **nil** if **key** doesn't exist and **defaultValue** is not specified.

======Related======

# [[Documentation#savelocaldata|saveLocalData]]
# [[Documentation#clearlocaldata|clearLocalData]]

----
=====saveLocalData( key, value )=====
======Examples======

{{{
#!lua
-- Save high score
saveLocalData('highscore', currentScore)
}}}

======Description======


This function stores a value associated with **key** in the local device storage for the current project.

\\
Local storage for a particular project is unique to your device. That is, sharing your project will not share the associated data. This sort of storage is useful for things such as high scores, statistics, and any values you are likely to associate while a user is interacting with your game or simulation.



======Syntax======

{{{
#!lua
saveLocalData( key, value )
}}}

======Parameters======

|=Name|=Description|
|key|string, name of the piece of data you would like to store|
|value|the value to store under **key**|

======Related======

# [[Documentation#readlocaldata|readLocalData]]
# [[Documentation#clearlocaldata|clearLocalData]]

----
=====clearLocalData()=====
======Description======


This function clears all local data for the current project.

\\
Local storage for a particular project is unique to your device. That is, sharing your project will not share the associated data. This sort of storage is useful for things such as high scores, statistics, and any values you are likely to associate while a user is interacting with your game or simulation.



======Syntax======

{{{
#!lua
clearLocalData( )
}}}

======Related======

# [[Documentation#readlocaldata|readLocalData]]
# [[Documentation#savelocaldata|saveLocalData]]

----
=====readProjectData( key )=====
======Description======


This function reads a value associated with **key** from the project storage for the current project.

\\
Project storage is bundled with your project. That is, sharing your project will also share the associated data. This sort of storage is useful for things such procedurally generated levels, maps, and other static or dynamic data you may want to provide with your project.



======Syntax======

{{{
#!lua
readProjectData( key )
readProjectData( key, defaultValue )
}}}

======Parameters======

|=Name|=Description|
|key|string, name of the piece of data you would like to get|
|defaultValue|if the key doesn't exist, this value is returned instead|

======Returns======


The value associated with **key**, or **defaultValue** if key doesn't exist and **defaultValue** is specified. **nil** if **key** doesn't exist and **defaultValue** is not specified.

======Related======

# [[Documentation#saveprojectdata|saveProjectData]]
# [[Documentation#clearprojectdata|clearProjectData]]

----
=====saveProjectData( key, value )=====
======Description======


This function stores a value associated with **key** in your project's storage.

\\
Project storage is bundled with your project. That is, sharing your project will also share the associated data. This sort of storage is useful for things such procedurally generated levels, maps, and other static or dynamic data you may want to provide with your project.



======Syntax======

{{{
#!lua
saveProjectData( key, value )
}}}

======Parameters======

|=Name|=Description|
|key|string, name of the piece of data you would like to store|
|value|the value to store under **key**|

======Related======

# [[Documentation#readprojectdata|readProjectData]]
# [[Documentation#clearprojectdata|clearProjectData]]

----
=====saveProjectInfo( key, value )=====
======Description======


This function allows you to save metadata about your project from within your code. For example, you may set the description that appears on the Project Browser page by calling **saveProjectInfo()** with 'description' as the key.



======Syntax======

{{{
#!lua
saveProjectInfo( key, value )
}}}

======Parameters======

|=Name|=Description|
|key|string, name of the project metadata to store. Currently supports "Description" and "Author"|
|value|the value to store under **key**|

======Related======

# [[Documentation#readprojectinfo|readProjectInfo]]

----
=====readProjectInfo( key )=====
======Description======


This function reads a value associated with **key** from the project metadata for the current project.



======Syntax======

{{{
#!lua
readProjectInfo( key )
}}}

======Parameters======

|=Name|=Description|
|key|string, name of the piece of metadata you would like to get|

======Returns======


The value associated with **key**, or nil if the key does not exist

======Related======

# [[Documentation#saveprojectinfo|saveProjectInfo]]

----
=====clearProjectData()=====
======Description======


This function clears all project-stored data.

\\
Project storage is bundled with your project. That is, sharing your project will also share the associated data. This sort of storage is useful for things such procedurally generated levels, maps, and other static or dynamic data you may want to provide with your project.



======Syntax======

{{{
#!lua
clearProjectData( )
}}}

======Related======

# [[Documentation#readprojectdata|readProjectData]]
# [[Documentation#saveprojectdata|saveProjectData]]

----
=====readGlobalData( key )=====
======Description======


This function reads a value associated with **key** from the global storage on this device.

\\
Global storage is shared among all projects on this device.



======Syntax======

{{{
#!lua
readGlobalData( key )
readGlobalData( key, defaultValue )
}}}

======Parameters======

|=Name|=Description|
|key|string, name of the piece of data you would like to get|
|defaultValue|if the key doesn't exist, this value is returned instead|

======Returns======


The value associated with **key**, or **defaultValue** if key doesn't exist and **defaultValue** is specified. **nil** if **key** doesn't exist and **defaultValue** is not specified.

======Related======

# [[Documentation#saveglobaldata|saveGlobalData]]
# [[Documentation#clearprojectdata|clearProjectData]]

----
=====saveGlobalData( key, value )=====
======Description======


This function stores a value associated with **key** in this device's global storage.

\\
Global storage is shared among all projects on this device.



======Syntax======

{{{
#!lua
saveGlobalData( key, value )
}}}

======Parameters======

|=Name|=Description|
|key|string, name of the piece of data you would like to store|
|value|the value to store under **key**|

======Related======

# [[Documentation#readglobaldata|readGlobalData]]

----

Updated