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.


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
  1. drawOverview
  2. 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).


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


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
  1. 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
clip( x, y, width, height )
clip() --Disables clipping
Parameters
NameDescription
xinteger, x coordinate of the lower-left corner of the clipping rectangle
yinteger, y coordinate of the lower-left corner of the clipping rectangle
widthinteger, width of the clipping rectangle
heightinteger, height of the clipping rectangle

setContext( image )
Examples
-- 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
setContext()
setContext( image )
Parameters
NameDescription
imageimage, all drawing operations will occur on this image instead of on screen
Related
  1. 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
noise( x )
noise( x, y )
noise( x, y, z )
Parameters
NameDescription
xfloat, x location of the sample
yfloat, y location of the sample
zfloat, 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
backingMode( STANDARD | RETAINED )
Parameters
NameDescription
modeOptional: either STANDARD or RETAINED
Returns

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

Related
  1. background

background( red, green, blue )
Examples
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
background( gray )
background( gray, alpha )
background( red, green, blue )
background( red, green, blue, alpha )
background( color )
Parameters
NameDescription
grayint from 0 to 255, specifies value between white and black
alphaint from 0 to 255, specifies opacity of the background
redint from 0 to 255, specifies red amount of the background
greenint from 0 to 255, specifies green amount of the background
blueint from 0 to 255, specifies blue amount of the background
colora value of the color datatype
Related
  1. color
  2. 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
ellipse( x, y, diameter )
ellipse( x, y, width, height )
Parameters
NameDescription
xx-coordinate of the ellipse
yy-coordinate of the ellipse
widthwidth of the ellipse
heightheight of the ellipse
Related
  1. ellipseMode
  2. fill
  3. 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
rect( x, y, width, height )
Parameters
NameDescription
xx-coordinate of the lower-left corner
yy-coordinate of the lower-left corner
widthwidth of the rectangle
heightheight of the rectangle
Related
  1. rectMode
  2. fill
  3. stroke

sprite( name, x, y )
Examples
background(127, 127, 127, 255)
sprite("Planet Cute:Character Boy",
	WIDTH / 2, HEIGHT / 2)
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
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
NameDescription
namename of the sprite to use, in the following format:
"SpritePack:SpriteName"
imageimage to draw onto the screen
xx-coordinate of the center of the sprite (this can be changed with spriteMode)
yy-coordinate of the center of the sprite (this can be changed with spriteMode)
widthoptional width of the sprite in pixels
heightoptional 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
  1. spriteMode
  2. tint
  3. noTint
  4. image

text( string, x, y )
Examples
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
text( string, x, y )
Parameters
NameDescription
stringthe text string that you would like to draw onto the screen
xx-coordinate of the center of the text (this can be changed with textMode)
yy-coordinate of the center of the text (this can be changed with textMode)
Related
  1. font
  2. fill
  3. fontSize
  4. textMode
  5. textAlign
  6. textWrapWidth
  7. textSize

line( x1, y1, x2, y2 )
Examples
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
line( x1, y1, x2, y2 )
Parameters
NameDescription
x1x-coordinate of the first point
y1y-coordinate of the first point
x2x-coordinate of the second point
y2y-coordinate of the second point
Returns

None

Related
  1. lineCapMode
  2. stroke
  3. strokeWidth
  4. smooth
  5. noSmooth

image
Examples
-- 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
image( width, height )
image.width
image.height
image(data)
Parameters
NameDescription
widthinteger, the width of the image in pixels
heightinteger, the height of the image in pixels
premultipliedboolean, tells Codea to render this image as a premultiplied image. The default is false.
datastring, a sequence of bytes representing the encoded jpeg or png image data.
Returns

The newly created image of given width and height

Related
  1. image.get
  2. image.set
  3. image.copy
  4. sprite
  5. setContext

image.get( x, y )
Examples
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
image.get( x, y )
Parameters
NameDescription
xinteger, x location of the pixel to query
yinteger, 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
  1. image
  2. image.set

image.set( x, y, color )
Examples
myImage:set( 15, 15, color(20,30,40,255) )
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
image.set( x, y, color )
image.set( x, y, r, g, b, a)
image.set( x, y, r, g, b)
Parameters
NameDescription
xinteger, x location of the pixel to query. 1 is the left most column. Must be less than or equal to the image.width value.
yinteger, y location of the pixel to query. 1 is the top most row. Must be less than or equal to the image.height value.
colorcolor object, the color to set the pixel to
r, g, b, ainteger, the red, green, blue and alpha value to set the pixel to. Between 0 and 255.
Related
  1. image
  2. image.set
  3. color

image.copy( x, y, w, h )
Examples
newImage = myImage:copy()
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
image:copy()
image:copy(x, y, width, height)
Parameters
NameDescription
xinteger, x location of the leftmost pixels of the copy region.
yinteger, y location of the topmost pixels of the copy region
widthpositive integer, width in pixels of the copy region
heightpositive 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
  1. image
  2. image.set

mesh
Examples
-- 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
m = mesh()
Parameters
NameDescription
verticestable, an array of vec2 or vec3 objects
colorstable, an array of color objects. If not set the global fill color is used for all vertices
texCoordstable, an array of vec2 objects. If not set, triangles are drawn with color only
texturestring or image, the texture to use when drawing this mesh. If not set, triangles are drawn with color only
validbool, true if this mesh is valid for drawing
sizeint, number of vertices in this mesh
Returns

The newly created empty mesh

Related
  1. color
  2. image
  3. spriteSize
  4. sprite
  5. vec3
  6. 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
myMesh:draw( m )
Parameters
NameDescription
mthe mesh to draw
Related
  1. 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
myMesh:setColors( c )
myMesh:setColors( r, g, b )
myMesh:setColors( r, g, b, a )
Parameters
NameDescription
mthe mesh to draw
Related
  1. 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
myMesh:clear()
Related
  1. 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
myMesh:addRect( x, y, w, h)
myMesh:addRect( x, y, w, h, r)
Parameters
NameDescription
xfloat, the x coordinate used to place the rectangle
yfloat, the y coordinate used to place the rectangle
yfloat, the y coordinate used to place the rectangle
wfloat, the width of the rectangle
hfloat, the height of the rectangle
rfloat, the rotation of the rectangle
Returns

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

Related
  1. mesh
  2. 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
myMesh:setRect( i, x, y, w, h)
myMesh:setRect( i, x, y, w, h, r)
Parameters
NameDescription
iint, the index of the rectangle in the mesh
xfloat, the x coordinate used to place the rectangle
yfloat, the y coordinate used to place the rectangle
yfloat, the y coordinate used to place the rectangle
wfloat, the width of the rectangle
hfloat, the height of the rectangle
rfloat, the rotation of the rectangle
Related
  1. mesh
  2. mesh.addRect
  3. mesh.setRectTex
  4. mesh.setRectColor

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

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

Syntax
myMesh:setRect( i, s, t, w, h)
Parameters
NameDescription
iint, the index of the rectangle in the mesh
sfloat, the left edge of the texture rectangle
tfloat, the bottom edge of the texture rectangle
wfloat, the width of the texture rectangle
hfloat, the height of the texture rectangle
Related
  1. mesh
  2. mesh.addRect
  3. mesh.setRect
  4. mesh.setRectColor

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

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

Syntax
myMesh:setRectColor( i, c)
myMesh:setRectColor( i, r, g, b)
myMesh:setRectColor( i, r, g, b, a)
Parameters
NameDescription
iint, the index of the rectangle in the mesh
ccolor, the color to set the rectangle to
rint, the red component of the color to use
gint, the green component of the color to use
bint, the blue component of the color to use
aint, the alpha component of the color to use
Related
  1. mesh
  2. mesh.addRect
  3. mesh.setRect
  4. 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
myMesh:vertex( i )
myMesh:vertex( i, x, y, z )
myMesh:vertex( i, vec3 )
myMesh:vertex( i, x, y )
myMesh:vertex( i, vec2 )
Parameters
NameDescription
iint, the index of the vertex in the mesh
xfloat, the x position to set vertex i to
yfloat, the y position to set vertex i to
zfloat, the z position to set vertex i to
vec3vec3, the 3D position to set vertex i to
vec2vec2, 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
  1. mesh
  2. mesh.texCoord
  3. 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
myMesh:texCoord( i )
myMesh:texCoord( i, x, y )
myMesh:texCoord( i, vec2 )
Parameters
NameDescription
iint, the index of the texture coordinate in the mesh
xfloat, the x value to set vertex i's texture coordinate to
yfloat, the y value to set vertex i's texture coordinate to
vec2vec2, 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
  1. mesh
  2. mesh.vertex
  3. 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
myMesh:color( i )
myMesh:color( i, r, g, b )
myMesh:color( i, r, g, b, a )
myMesh:color( i, color )
Parameters
NameDescription
iint, the index of the color in the mesh
rint, the red value to set vertex i's color to (0 to 255)
gint, the green value to set vertex i's color to (0 to 255)
bint, the blue value to set vertex i's color to (0 to 255)
aint, the alpha value to set vertex i's color to (0 to 255)
colorcolor, 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
  1. mesh
  2. mesh.vertex
  3. mesh.texCoord
  4. color

triangulate( points )
Description

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

Syntax
triangleVertices = triangulate( points )
Parameters
NameDescription
pointstable, 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
translate( x, y )
translate( x, y, z )
Parameters
NameDescription
xamount of horizontal translation, in pixels
yamount of vertical translation, in pixels
zamount of depth translation, in pixels
Related
  1. rotate
  2. scale
  3. pushMatrix
  4. popMatrix
  5. 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
rotate( angle )
rotate( angle, x, y, z )
Parameters
NameDescription
angleamount of rotation in degrees
xfloat, x value for the axis of rotation
yfloat, y value for the axis of rotation
zfloat, z value for the axis of rotation
Related
  1. translate
  2. scale
  3. pushMatrix
  4. 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
scale( amount )
scale( x, y )
scale( x, y, z )
Parameters
NameDescription
amountuniform amount of scale to apply horizontally and vertically. Applies on all axis, x, y and z.
xamount of scale to apply on the x axis (horizontal)
yamount of scale to apply on the y axis (vertical)
zamount of scale to apply on the z axis (depth)
Related
  1. rotate
  2. translate
  3. pushMatrix
  4. 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
zLevel( z )
Parameters
NameDescription
zfloat, the amount of depth for future drawing operations, use positive values to draw in front, and negative values to draw behind.
Related
  1. transform
  2. pushMatrix
  3. 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
perspective()
perspective( fov )
perspective( fov, aspect )
perspective( fov, aspect, near, far )
Parameters
NameDescription
fovfloat, field of view in degrees
aspectfloat, aspect ratio of the screen. Defaults to WIDTH/HEIGHT
nearfloat, near clipping plane, defaults to 0.1
farfloat, far clipping plane, default value is computed based on the height of the screen
Related
  1. projectionMatrix
  2. ortho
  3. camera
  4. matrix
  5. WIDTH
  6. 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
ortho()
ortho( left, right, bottom, top )
ortho( left, right, bottom, top, near, far )
Parameters
NameDescription
leftfloat, left edge of the frustum
rightfloat, right edge of the frustum
bottomfloat, bottom edge of the frustum
topfloat, top edge of the frustum
Related
  1. projectionMatrix
  2. perspective
  3. camera
  4. matrix
  5. WIDTH
  6. 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
camera( eyeX, eyeY, eyeZ,
        centerX, centerY, centerZ,
        upX, upY, upZ )
Parameters
NameDescription
eyeX/Y/Zfloats, position of the "eye" in 3D
centerX/Y/Zfloats, coordinate to look at
upX/Y/Zfloats, up-vector of the camera, defaults to (0, 1, 0)
Related
  1. viewMatrix
  2. perspective
  3. matrix
  4. WIDTH
  5. 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
applyMatrix( matrix )
Parameters
NameDescription
matrixmatrix, the transformation to multiply against the current world transform
Related
  1. modelMatrix
  2. matrix
  3. pushMatrix
  4. 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
modelMatrix()
modelMatrix( matrix )
Parameters
NameDescription
matrixmatrix, the transformation to set as the current world transform
Returns

The current model matrix when called with no arguments

Related
  1. viewMatrix
  2. projectionMatrix
  3. matrix
  4. 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
viewMatrix()
viewMatrix( matrix )
Parameters
NameDescription
matrixmatrix, the transformation to set as the current view transform
Returns

The current view matrix when called with no arguments

Related
  1. modelMatrix
  2. camera
  3. projectionMatrix
  4. 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
projectionMatrix()
projectionMatrix( matrix )
Parameters
NameDescription
matrixmatrix, the transformation to set as the current projection transform
Returns

The current projection matrix when called with no arguments

Related
  1. modelMatrix
  2. perspective
  3. ortho
  4. viewMatrix
  5. matrix

color
Examples
--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
color.r
color.g
color.b
color.a
myColor = color( 255, 0, 0, 255 ) --red
Parameters
NameDescription
rfloat, the red component of this color from 0 to 255
gfloat, the green component of this color from 0 to 255
bfloat, the blue component of this color from 0 to 255
afloat, the alpha component of this color from 0 to 255
Related
  1. fill
  2. stroke
  3. tint
  4. background

ellipseMode( MODE )
Description

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

Syntax
ellipseMode()
ellipseMode( CENTER|RADIUS|CORNER|CORNERS )
Parameters
NameDescription
modeeither 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
  1. ellipse

rectMode( MODE )
Description

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

Syntax
rectMode()
rectMode( CENTER|RADIUS|CORNER|CORNERS )
Parameters
NameDescription
modeeither 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
  1. rect

spriteMode( MODE )
Description

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

Syntax
spriteMode()
spriteMode( CENTER|RADIUS|CORNER|CORNERS )
Parameters
NameDescription
modeeither 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
  1. 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
w, h = spriteSize("Planet Cute:Character Boy")
w, h = spriteSize( image )
Parameters
NameDescription
namename of a sprite, in the form "Sprite Pack:Sprite Name"
imageimage object
Returns

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

Related
  1. sprite
  2. image

textMode( MODE )
Description

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

Syntax
textMode()
textMode( CENTER|CORNER )
Parameters
NameDescription
modeeither 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
  1. text

lineCapMode( MODE )
Examples
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
lineCapMode()
lineCapMode( ROUND | SQUARE | PROJECT )
Parameters
NameDescription
modeeither ROUND, SQUARE or PROJECT


ROUNDline ends are rounded with circles


SQUAREline ends are squared off at the end points


PROJECTline 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
  1. line
  2. stroke
  3. 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
fill()
fill( gray )
fill( gray, alpha )
fill( red, green, blue )
fill( red, green, blue, alpha )
fill( color )
Parameters
NameDescription
grayint from 0 to 255, specifies value between white and black
alphaint from 0 to 255, specifies opacity of the fill
redint from 0 to 255, specifies red amount of the fill
greenint from 0 to 255, specifies green amount of the fill
blueint from 0 to 255, specifies blue amount of the fill
colora 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
  1. noFill
  2. stroke
  3. color

noFill()
Description

Sets the color of the fill to completely transparent.

Syntax
noFill()
Related
  1. fill
  2. noStroke

tint( red, green, blue, alpha )
Examples
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
tint()
tint( gray )
tint( gray, alpha )
tint( red, green, blue )
tint( red, green, blue, alpha )
tint( color )
Parameters
NameDescription
grayint from 0 to 255, specifies value between white and black
alphaint from 0 to 255, specifies opacity of the tint
redint from 0 to 255, specifies red amount of the tint
greenint from 0 to 255, specifies green amount of the tint
blueint from 0 to 255, specifies blue amount of the tint
colora 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
  1. sprite
  2. noTint

noTint()
Description

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

Syntax
noTint()
Related
  1. tint
  2. 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
stroke()
stroke( gray )
stroke( gray, alpha )
stroke( red, green, blue )
stroke( red, green, blue, alpha )
stroke( color )
Parameters
NameDescription
grayint from 0 to 255, specifies value between white and black
alphaint from 0 to 255, specifies opacity of the stroke
redint from 0 to 255, specifies red amount of the stroke
greenint from 0 to 255, specifies green amount of the stroke
blueint from 0 to 255, specifies blue amount of the stroke
colora 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
  1. strokeWidth
  2. noStroke
  3. 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
strokeWidth()
strokeWidth( width )
Parameters
NameDescription
widthint 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
  1. stroke
  2. noStroke

noStroke()
Description

Sets the stroke width to zero.

Syntax
noStroke()
Related
  1. stroke
  2. strokeWidth

smooth()
Description

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

Syntax
smooth()
Related
  1. noSmooth
  2. line
  3. lineCapMode

noSmooth()
Description

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

Syntax
noSmooth()
Related
  1. smooth
  2. line
  3. 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
font()
font( name )
Parameters
NameDescription
namestring, the name of the font to use. For iOS devices, this can be one of the following:


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
  1. text
  2. 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
fontSize()
fontSize( size )
Parameters
NameDescription
sizefloat, 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
  1. text
  2. 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
fontMetrics()
Returns

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

**

Related
  1. font
  2. 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
textAlign()
textAlign( LEFT|CENTER|RIGHT )
Parameters
NameDescription
ALIGNCan be LEFT, CENTER or RIGHT
Returns

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

Related
  1. text
  2. textWrapWidth

textWrapWidth( width )
Examples
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
textWrapWidth()
textWrapWidth( width )
Parameters
NameDescription
widthfloat, 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
  1. text
  2. textAlign

textSize( string )
Examples
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
width = textSize( string )
width, height = textSize( string )
Parameters
NameDescription
stringstring, the string to measure
Returns

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

Related
  1. 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
pushMatrix()
Related
  1. popMatrix
  2. resetMatrix
  3. translate
  4. rotate
  5. 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
popMatrix()
Related
  1. pushMatrix
  2. resetMatrix
  3. translate
  4. rotate
  5. 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
popMatrix()
Related
  1. pushMatrix
  2. 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
resetMatrix()
Related
  1. pushMatrix
  2. popMatrix
  3. translate
  4. rotate
  5. 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
pushStyle()
Related
  1. popStyle
  2. 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
popStyle()
Related
  1. pushStyle
  2. 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
resetStyle()
Related
  1. pushStyle
  2. popStyle

WIDTH
Description

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

Syntax
WIDTH
Returns

Width of the screen in pixels

Related
  1. HEIGHT

HEIGHT
Description

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

Syntax
HEIGHT
Returns

Height of the screen in pixels

Related
  1. WIDTH

ElapsedTime
Description

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

Syntax
ElapsedTime
Returns

Time in seconds since the start of running the project

Related
  1. DeltaTime

DeltaTime
Description

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

Syntax
DeltaTime
Returns

Time in seconds since the start of the previous frame

Related
  1. 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
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

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

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

-- 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
  1. ipairs
  2. pairs

Conditionals Overview
Description

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


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


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


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

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
for i,v in ipairs( t ) do body end

-- This will iterate over the pairs:
--   (1,t[1]), (2,t[2]), ...
Parameters
NameDescription
tabletable to iterate over
Returns

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

Related
  1. forloops
  2. 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
for k,v in pairs( t ) do body end

-- This will iterate over all key-value
-- pairs in table t
Parameters
NameDescription
tabletable to iterate over
Returns

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

Related
  1. forloops
  2. 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
table.concat( table )
table.concat( table, sep )
table.concat( table, sep, i )
table.concat( table, sep, i, j )
Parameters
NameDescription
tabletable to concatenate
sepseparator string
iint, starting index to concatenate from
jint, 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
table.insert( table, value )
table.insert( table, pos, value )
Parameters
NameDescription
tabletable to insert into
posint, position to inset
valuevalue to insert
Related
  1. 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
table.maxn( table )
Parameters
NameDescription
tabletable 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
table.remove( table )
table.remove( table, pos )
Parameters
NameDescription
tabletable to insert into
posint, position of value to remove
Returns

Value of the removed element

Related
  1. 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
table.sort( table )
table.sort( table, comp )
Parameters
NameDescription
tablethe table to sort
compa 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
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
os.difftime( t2, t1 )
Parameters
NameDescription
t2Ending time
t1Starting time
Returns

Number of seconds from time t1 to time t2.

Related
  1. 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
os.date()
os.date( format )
os.date( format, time )
Parameters
NameDescription
formatString used to format the returned date
timeIf 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
  1. os.time
  2. 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
os.setlocale( locale )
os.setlocale( locale, category )
Parameters
NameDescription
localeString specifying a locale, can be nil or the empty string.
categoryString 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
  1. os.date
  2. 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
os.time()
os.time( table )
Parameters
NameDescription
tableThis 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
  1. os.date
  2. os.setlocale
  3. 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
string.find( s, pattern )
string.find( s, pattern, init )
string.find( s, pattern, init, plain )
Parameters
NameDescription
sstring to search in
patternpattern to look for
initstarting character in string to search from, default is 1
plainboolean, 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
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
string.format( formatstring, ... )
Parameters
NameDescription
formatstringstring 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
string.len( s )
Parameters
NameDescription
sget 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
string.lower( s )
Parameters
NameDescription
sget a lowercase version of this string
Returns

Lowercase version of string s

Related
  1. 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
string.upper( s )
Parameters
NameDescription
sget an uppercase version of this string
Returns

Uppercase version of string s

Related
  1. 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
string.match( s, pattern )
string.match( s, pattern, init )
Parameters
NameDescription
sstring to search
patternpattern to match
initstarting location in string
Returns

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

Related
  1. string.find

string.rep( s, n )
Description

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

Syntax
string.rep( s, n )
Parameters
NameDescription
sstring to replicate
nint, 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
string.sub( s, i )
string.sub( s, i, j )
Parameters
NameDescription
sfind substring of this string
iint, starting index
jint, 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
math.abs( value )
Parameters
NameDescription
valueint 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
math.acos( value )
Parameters
NameDescription
valueint or float, compute the arc cosine of this number
Returns

The arc cosine of value in radians

Related
  1. math.asin
  2. math.atan
  3. math.atan2

math.asin( value )
Description

This function returns the arc sine of value in radians

Syntax
math.asin( value )
Parameters
NameDescription
valueint or float, compute the arc sine of this number
Returns

The arc sine of value in radians

Related
  1. math.acos
  2. math.atan
  3. math.atan2

math.atan( value )
Description

This function returns the arc tangent of value in radians

Syntax
math.atan( value )
Parameters
NameDescription
valueint or float, compute the arc tangent of this number
Returns

The arc tangent of value in radians

Related
  1. math.asin
  2. math.acos
  3. 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
math.atan2( x, y )
Parameters
NameDescription
xint or float, denominator for arc tangent
yint or float, numerator for arc tangent
Returns

The arc tangent of y/x in radians

Related
  1. math.asin
  2. math.acos
  3. 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
math.ceil( value )
Parameters
NameDescription
valueint or float, compute the smallest integer larger than or equal to this number
Returns

The smallest integer larger than or equal to value

Related
  1. math.floor

math.cos( value )
Description

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

Syntax
math.cos( value )
Parameters
NameDescription
valueint or float, compute the cosine of this number
Returns

Cosine of value

Related
  1. math.sin
  2. math.tan

math.cosh( value )
Description

This function returns hyperbolic cosine of value.

Syntax
math.cosh( value )
Parameters
NameDescription
valueint or float, compute the hyperbolic cosine of this number
Returns

Hyperbolic cosine of value

Related
  1. math.sinh
  2. math.tanh

math.deg( value )
Description

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

Syntax
math.deg( value )
Parameters
NameDescription
valueint or float, angle in radians to convert to degrees
Returns

Angle specified by value (in radians) in degrees

Related
  1. math.rad

math.rad( value )
Description

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

Syntax
math.rad( value )
Parameters
NameDescription
valueint or float, angle in degrees to convert to radians
Returns

Angle specified by value (in degrees) in radians

Related
  1. math.deg

math.exp( value )
Description

This function returns e raised to value

Syntax
math.exp( value )
Parameters
NameDescription
valueint 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
math.floor( value )
Parameters
NameDescription
valueint or float, compute the largest integer smaller than or equal to this number
Returns

The largest integer smaller than or equal to value

Related
  1. 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
math.fmod( x, y )
Parameters
NameDescription
xint or float
yint or float
Returns

The remainder of the division of x by y

Related
  1. 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
math.frexp( value )
Parameters
NameDescription
valueint 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
  1. math.ldexp

math.ldexp( m, e )
Description

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

Syntax
math.ldexp( m, e )
Parameters
NameDescription
mint or float
mint
Returns

m2^e

Related
  1. math.frexp

math.log( value )
Description

This function returns the natural logarithm of value

Syntax
math.log( value )
Parameters
NameDescription
valueint or float, compute the natural logarithm of this value
Returns

The natural logarithm of value

Related
  1. math.log10

math.log10( value )
Description

This function returns the base-10 logarithm of value

Syntax
math.log10( value )
Parameters
NameDescription
valueint or float, compute the base-10 logarithm of this value
Returns

The base-10 logarithm of value

Related
  1. math.log

math.max( value, ... )
Description

This function returns maximum value among its arguments.

Syntax
math.max( value, ... )
Parameters
NameDescription
valueany comparable value
Returns

The maximum value among its arguments

Related
  1. math.min

math.min( value, ... )
Description

This function returns minimum value among its arguments.

Syntax
math.min( value, ... )
Parameters
NameDescription
valueany comparable value
Returns

The minimum value among its arguments

Related
  1. math.max

math.modf( value )
Description

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

Syntax
math.modf( value )
Parameters
NameDescription
valueint or float
Returns

Two numbers, the integral part of value and the fractional part of value

Related
  1. math.fmod

math.pow( x, y )
Description

This function returns x raised to y. Equivalent to the expression x^y.

Syntax
math.pow( x, y )
Parameters
NameDescription
xint or float
yint or float
Returns

x raised to y

Related
  1. 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
math.random()
math.random( maximum )
math.random( minimum, maximum )
Parameters
NameDescription
minimumint, minimum value of returned pseudo-random number
maximumint, maximum value of returned pseudo-random number
Returns

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

Related
  1. 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
math.randomseed( value )
Parameters
NameDescription
valueint, seed of the pseudo-random number generator
Returns

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

Related
  1. math.random

math.sin( value )
Description

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

Syntax
math.sin( value )
Parameters
NameDescription
valueint or float, compute the sine of this number
Returns

Sine of value

Related
  1. math.cos
  2. math.tan

math.sinh( value )
Description

This function returns hyperbolic sine of value.

Syntax
math.sinh( value )
Parameters
NameDescription
valueint or float, compute the hyperbolic sine of this number
Returns

Hyperbolic sine of value

Related
  1. math.cosh
  2. math.tanh

math.tan( value )
Description

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

Syntax
math.tan( value )
Parameters
NameDescription
valueint or float, compute the tangent of this number
Returns

Tangent of value

Related
  1. math.sin
  2. math.cos

math.tanh( value )
Description

This function returns hyperbolic tangent of value.

Syntax
math.tanh( value )
Parameters
NameDescription
valueint or float, compute the hyperbolic tangent of this number
Returns

Hyperbolic tangent of value

Related
  1. math.sinh
  2. 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
math.sqrt( value )
Parameters
NameDescription
valueint or float, compute the square root of this number
Returns

Square root of value

Related
  1. math.pow

math.huge
Description

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

Syntax
math.huge
Returns

A value larger than or equal to any other numerical value


math.pi
Description

The value of pi.

Syntax
math.pi
Returns

Value of pi


Touch

Detecting and Reacting to Touches on the Screen


CurrentTouch
Examples
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
CurrentTouch
Related
  1. touch

touch
Description

This type represents data about a single touch on the screen.

Syntax
touch.id
touch.x
touch.y
touch.prevX
touch.prevY
touch.deltaX
touch.deltaY
touch.state
touch.tapCount
Parameters
NameDescription
idint, a unique identifier for this touch
xfloat, specifies the x position of the touch on the screen
yfloat, specifies the y position of the touch on the screen
prevXfloat, specifies the x position, from the previous frame, of the touch on the screen
prevYfloat, specifies the y position, from the previous frame, of the touch on the screen
deltaXfloat, specifies the x delta since the last frame, the amount the touch has moved
deltaYfloat, specifies the y delta since the last frame, the amount the touch has moved
statethe state of the touch, can be BEGAN, MOVING or ENDED
tapCounthow many times the touch has been tapped
Related
  1. CurrentTouch

Parameters

Creating Parameters to Control Your Projects


parameter( name, min, max )
Examples
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
parameter( name )
parameter( name, min, max )
parameter( name, min, max, initial )
Parameters
NameDescription
namestring, the parameter function will create a global variable with this name
minint or float, specifies the minimum value that your parameter can take
maxint or float, specifies the maximum value that your parameter can take
initialint or float, specifies the initial, or starting, value of the parameter
Related
  1. iparameter

iparameter( name, min, max )
Examples
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
iparameter( name )
iparameter( name, min, max )
iparameter( name, min, max, initial )
Parameters
NameDescription
namestring, the parameter function will create a global variable with this name
minint, specifies the minimum value that your parameter can take
maxint, specifies the maximum value that your parameter can take
initialint, specifies the initial, or starting, value of the parameter
Related
  1. 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
clearParameters()
Related
  1. parameter
  2. iparameter
  3. watch

clearOutput()
Description

This function clears the output buffer for the print() function.

Syntax
clearOutput()

watch( name )
Examples
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
watch( name )
Parameters
NameDescription
namestring, the global variable to watch

Physics

Dynamic Motion with Forces, Joints and Collisions


physics.body
Examples
-- create a circle with 25px radius
circle = physics.body(CIRCLE, 25)
Description

This type represents a dynamic rigid body.

Syntax
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
NameDescription
typeint, the type of the body, can be STATIC, DYNAMIC or KINEMATIC
shapeTypereadonly, the shape type of the body, can be CIRCLE, POLYGON, CHAIN or EDGE
radiusfloat, the radius of the body, only valid for circle shape types
pointstable, a table containing the point that make up the body, only valid for polygon shape types
xfloat, the x position of the body in pixels
yfloat, the y position of the body in pixels
positionvec2, the position of the body wrapped in a vector
anglefloat, the angle of the body in degrees
linearVelocityvec2, the current linear velocity of the body in pixels per second
angularVelocityfloat, the angular velocity of the body in degrees per second
densityfloat, the density of the body in kg/m^2, 1 by default, cannot be negative
massfloat, the mass of the body in kg, cannot be negative. If you set this, density will be ignored
inertiafloat, the momoment of inertia of the body. Cannot be set
restitutionfloat, the restitution, or 'bouncyness' of the body
frictionfloat, the friction of the body determines how easy the object slides
fixedRotationboolean, locks the rotation of this body
activeboolean, set to false to remove from simulation
awakeboolean, true if body is currently awake, false otherwise
sleepingAllowedboolean, set to false to prevent bodies from sleeping (default: true)
bulletboolean, set to true for fast moving bodies to prevent tunneling
gravityScalefloat, controls the influence of gravity on this body, 1 by default
interpolateboolean, controls render interpolation, used to smooth out motion but introduces slight lag
infovalue, used for storing arbitrary data in this body
Related
  1. 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
CIRCLE
Returns

int

Related
  1. 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
POLYGON
Returns

int

Related
  1. 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
CHAIN
Returns

int

Related
  1. 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
EDGE
Returns

int

Related
  1. physics.body

DYNAMIC
Description

This constant specifies the dynamic body type.

Dynamic bodies move under the influence of collisions, forces, joints and gravity.

Syntax
DYNAMIC
Returns

int

Related
  1. 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
STATIC
Returns

int

Related
  1. 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
KINEMATIC
Returns

int

Related
  1. physics.body

physics.joint
Description

This type represents a joint that constrains two rigid bodies together.

Syntax
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
NameDescription
typeint, the type of the joint, can be REVOLUTE, DISTANCE, PRISMATIC or WELD
bodyAbody, the first body attached to this joint
bodyBbody, the second body attached to this joint
anchorAvec2, the anchor for the first body in world coordinates
anchorBvec2, the anchor for the second body in world coordinates
reactionForcevec2, 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
reactionTorquefloat, 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
enableLimitboolean, whether or not the limit for this joint is enabled. Only certain joints, such as REVOLUTE and PRISMATIC have limits
lowerLimitfloat, 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
upperLimitfloat, 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
enableMotorboolean, whether or not the motor for this joint is enabled. Only certain joints, such as REVOLUTE and PRISMATIC have motors
motorSpeedfloat, 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
maxMotorTorquefloat, the maximum amount of torque the motor can apply to reach the desired motor speed. Only REVOLUTE joints have this property
maxMotorForcefloat, the maximum amount of force the motor can apply to reach the desired motor speed. Only PRISMATIC joints have this property
lengthfloat, the length of the joint. Only applies to DISTANCE joints
frequencyfloat, The softness of the joint, set to zero for stiff joints. Only applies to DISTANCE and WELD joints
dampingRatiofloat, Controls the damping of soft joints, higher values reduce oscillation, set to zero for stiff joints. Only applies to DISTANCE and WELD joints
Related
  1. 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
REVOLUTE
Returns

int

Related
  1. 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
DISTANCE
Returns

int

Related
  1. 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
PRISMATIC
Returns

int

Related
  1. 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
WELD
Returns

int

Related
  1. 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.


-- 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
  1. physics.contact

physics.contact
Examples
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

Parameters
NameDescription
idnumber, a unique id that represents this contact
stateint, the current state of this contact, can be BEGAN, PERSIST, ENDED
touchingbool, whether or not the contact is currently touching. Due to the way contacts are cached this can be false under some circumstances.
positionvec2, the current position of this contact
normalvec2, the current normal of this contact
normalImpulsefloat, the magnitude of energy used to separate the two colliding bodies projected along the normal vector. Useful for measuring the strength of an impact
normalImpulsefloat, 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
pointCountint, the number of points in the contact manifold
pointstable, an array of vec2's describing the contact manifold
bodyAbody, the first body in the collision represented by this contact
bodyBbody, the second body in the collision represented by this contact
Related
  1. physics.body
  2. physics.joint

body.applyForce( force )
Description

Applies a force to this body object.

Syntax
myBody:applyForce( force )
myBody:applyForce( force, worldPoint )
Parameters
NameDescription
forcevec2, the amount of force to apply as a vector
worldPointvec2, the point to apply the force from, in world coordinates
Related
  1. physics.body
  2. body.applyTorque

body.applyTorque( torque )
Description

Applies torque to this body object.

Syntax
myBody:applyTorque( applyTorque )
Parameters
NameDescription
torquefloat, the amount of torque
Related
  1. physics.body
  2. body.applyForce

body.destroy()
Examples
-- 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
myBody:destroy()
Related
  1. physics.body
  2. body.applyForce
  3. body.destroy

body.testPoint( worldPoint )
Examples
-- 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
testPoint( worldPoint )
Parameters
NameDescription
worldPointvec2, the point to test for intersection, in world space
Returns

true if worldPoint is inside this body, false otherwise

Related
  1. physics.body
  2. body.applyForce
  3. body.destroy
  4. body.testPoint

body.testOverlap( otherBody )
Examples
-- 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
testOverlap( otherBody )
Parameters
NameDescription
otherBodybody, the body to test for intersection with
Returns

true if this body is intersecting with otherBody, false otherwise

Related
  1. physics.body
  2. body.applyForce
  3. body.destroy
  4. body.testPoint

body.getLocalPoint( worldPoint )
Examples
-- TODO example
Description

Converts a point to the local coordinate space of this body

Syntax
myBody:getLocalPoint( worldPoint )
Returns

vec2, coordinate in local space of this body

Related
  1. physics.body
  2. body.applyForce
  3. body.destroy
  4. body.testPoint

body.getWorldPoint( localPoint )
Examples
-- TODO example
Description

Converts a point from the local coordinate space of this body to world space

Syntax
myBody:getWorldPoint( localPoint )
Returns

vec2, coordinate in world space

Related
  1. physics.body
  2. body.applyForce
  3. body.destroy
  4. body.testPoint

body.getLinearVelocityFromWorldPoint( point )
Examples
-- TODO example
Description

Samples the linear velocity of this body at a given point in world space.

Syntax
myBody:getLinearVelocityFromWorldPoint( worldPoint )
Returns

vec2, linear velocity at worldPoint of this body

Related
  1. physics.body
  2. body.applyForce
  3. body.destroy
  4. body.testPoint

body.getLinearVelocityFromLocalPoint( point )
Examples
-- TODO example
Description

Samples the linear velocity of this body at a given point in local space.

Syntax
myBody:getLinearVelocityFromLocalPoint( worldPoint )
Returns

vec2, linear velocity at localPoint of this body

Related
  1. physics.body
  2. body.applyForce
  3. body.destroy
  4. body.testPoint

physics.pause()
Description

Pauses the physics simulation.

Syntax
-- pause physics
physics.pause()
Related
  1. physics.resume

physics.resume()
Description

Resumes the physics simulation.

Syntax
-- resume physics
physics.resume()
Related
  1. 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
physics.raycast(start, end)
physics.raycast(start, end, category1)
physics.raycast(start, end, category1, category2)
Parameters
NameDescription
startvec2, the start point of the ray (technically a line segment, but finite for practical purposes)
endvec2, 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
  1. physics.raycastAll
  2. 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
physics.raycastAll(start, end)
physics.raycastAll(start, end, category1)
physics.raycastAll(start, end, category1, category2)
Parameters
NameDescription
startvec2, the start point of the ray (technically a line segment, but finite for practical purposes)
endvec2, 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
  1. physics.raycast
  2. 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
physics.queryAABB(lowerLeft, upperRight)

physics.queryAABB(lowerLeft, upperRight, category1)

physics.queryAABB(lowerLeft, upperRight,
                  category1, category2)
Parameters
NameDescription
lowerLeftvec2, the position of the lower left corner of the query axis-aligned bounding box
upperRightvec2, 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
  1. physics.raycast
  2. physics.raycastAll
  3. 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
physics.gravity( x, y )
physics.gravity( grav )
physics.gravity( Gravity )
Parameters
NameDescription
xfloat, gravity in the x-axis
yfloat, gravity in the y-axis
gravvec2, gravity in both axes
Gravityvec3, device gravity used as a special case
Returns

vec2, the current world gravity if no parameters are supplied

Related
  1. physics.iterations
  2. 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
physics.iterations( velocityIterations,
                    positionIterations )
Parameters
NameDescription
velocityIterationsint, the number of velocity iterations performed each time step (default: 10)
positionIterationsint, the number of position iterations performed each time step (default: 8)
Related
  1. physics.gravity
  2. 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
physics.pixelToMeterRatio( ptmRatio )
physics.pixelToMeterRatio()
Parameters
NameDescription
ptmRatioint, the number of pixels per meter (default: 32)
Returns

int, the current ratio (when no parameters are supplied)

Related
  1. physics.gravity
  2. physics.iterations

Sounds

Playing and Generating Sound Effects


sound( name, seed )
Examples
-- using a string
sound( "jump", 1234 )
-- using the predefined constant
sound( SOUND_JUMP, 1234 )
-- 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
sound( name )
sound( name, seed )
sound( parameter_table )
sound( buffer )
Parameters
NameDescription
namestring, 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|

seedint, specifies the random seed to use when generating a sound of this type
buffersoundbuffer, specifies the raw sound data to play
parameter_tabletable, 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
  1. SOUND_BLIT
  2. SOUND_EXPLODE
  3. SOUND_HIT
  4. SOUND_JUMP
  5. SOUND_PICKUP
  6. SOUND_POWERUP
  7. SOUND_RANDOM
  8. SOUND_SHOOT
  9. SOUND_NOISE
  10. sound buffer
  11. SOUND_SQUAREWAVE
  12. SOUND_SINEWAVE
  13. SOUND_SAWTOOTH

soundbuffer( data, format, freq )
Examples
-- 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
soundbuffer( data, format, freq )
Parameters
NameDescription
datastring, uncompressed audio data
formatFORMAT_MONO8, FORMAT_MONO16, FORMAT_STEREO8 or FORMAT_STEREO16
freqinteger, the frequency of the data
Returns

A new soundbuffer object

Related
  1. sound

soundBufferSize( size )
Examples
-- setting the sound buffer maximum size
soundBufferSize( 3 )
-- reading the current maximum size and used size
maxSize, usedSize = nsoundBufferSize()
-- 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
soundBufferSize( size )
soundBufferSize()
Parameters
NameDescription
sizenumber, 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
  1. sound

SOUND_JUMP
Description

This constant specifies a jump sound. Similar to a character jumping in a platform game.

Syntax
SOUND_JUMP
Returns

The string "jump"

Related
  1. sound

SOUND_HIT
Description

This constant specifies a hit sound. For example, when the enemy collides with the player.

Syntax
SOUND_HIT
Returns

The string "hit"

Related
  1. sound

SOUND_PICKUP
Description

This constant specifies a pickup sound. For example, collecting coins in a game.

Syntax
SOUND_PICKUP
Returns

The string "pickup"

Related
  1. sound

SOUND_POWERUP
Description

This constant specifies a powerup sound. For example, collecting bonuses in a game.

Syntax
SOUND_POWERUP
Returns

The string "powerup"

Related
  1. sound

SOUND_SHOOT
Description

This constant specifies a shooting sound. For example, firing a bullet in a game.

Syntax
SOUND_SHOOT
Returns

The string "shoot"

Related
  1. sound

SOUND_EXPLODE
Description

This constant specifies an explosion sound. For example, a space ship blowing up.

Syntax
SOUND_EXPLODE
Returns

The string "explode"

Related
  1. sound

SOUND_BLIT
Description

This constant specifies a generic "blit" sound.

Syntax
SOUND_BLIT
Returns

The string "blit"

Related
  1. 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
SOUND_RANDOM
Returns

The string "random"

Related
  1. sound

SOUND_NOISE
Description

This specifices to use a white noise function as the waveform for this sound

Syntax
SOUND_NOISE
Returns

The integer 3

Related
  1. sound

SOUND_SAWTOOTH
Description

This specifices to use a sawtooth function as the waveform for this sound

Syntax
SOUND_SAWTOOTH
Returns

The integer 1

Related
  1. sound

SOUND_SINEWAVE
Description

This specifices to use a sine wave function as the waveform for this sound

Syntax
SOUND_SINEWAVE
Returns

The integer 2

Related
  1. sound

SOUND_SQUAREWAVE
Description

This specifices to use a square wave function as the waveform for this sound

Syntax
SOUND_SQUAREWAVE
Returns

The integer 0

Related
  1. sound

Display &amp; Keyboard

Using the Viewer's Display Modes


displayMode( MODE )
Examples
function setup()
    --Set the viewer to fullscreen
    displayMode( FULLSCREEN )
end
function setup()
    --Set the viewer to standard
    --i.e. visible parameters and output
    displayMode( STANDARD )
end
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
displayMode( STANDARD |
             FULLSCREEN |
             FULLSCREEN_NO_BUTTONS )
Parameters
NameDescription
modeEither STANDARD, FULLSCREEN or FULLSCREEN_NO_BUTTONS
Related
  1. STANDARD
  2. FULLSCREEN
  3. 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
FULLSCREEN
Related
  1. 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
displayMode( STANDARD )
backingMode( STANDARD )
Related
  1. displayMode
  2. 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
FULLSCREEN_NO_BUTTONS
Related
  1. displayMode
  2. close

Orientation Overview
Examples
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
  1. supportedOrientations
  2. 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
  1. PORTRAIT
  2. PORTRAIT_UPSIDE_DOWN
  3. LANDSCAPE_LEFT
  4. LANDSCAPE_RIGHT

supportedOrientations( ORIENTATION, ... )
Examples
supportedOrientations(PORTRAIT_ANY)

function setup()
    --Only support portrait orientations
end
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
supportedOrientations()
supportedOrientations( orient1, orient2, … )
Parameters
NameDescription
orientationCan 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
  1. ANY
  2. PORTRAIT_ANY
  3. PORTRAIT
  4. PORTRAIT_UPSIDE_DOWN
  5. LANDSCAPE_ANY
  6. LANDSCAPE_LEFT
  7. LANDSCAPE_RIGHT

ANY
Description

Use this value in supportedOrientation() to allow the viewer to assume any orientation when the device is rotated.

Syntax
supportedOrientation( ANY )
Related
  1. 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
supportedOrientation( PORTRAIT_ANY )
Related
  1. supportedOrientations
  2. PORTRAIT
  3. 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
supportedOrientation( PORTRAIT )
Related
  1. supportedOrientations
  2. 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
supportedOrientation( PORTRAIT_UPSIDE_DOWN )
Related
  1. supportedOrientations
  2. 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
supportedOrientation( LANDSCAPE_ANY )
Related
  1. supportedOrientations
  2. LANDSCAPE_LEFT
  3. 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
supportedOrientation( LANDSCAPE_LEFT )
Related
  1. supportedOrientations
  2. 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
supportedOrientation( LANDSCAPE_RIGHT )
Related
  1. supportedOrientations
  2. 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.


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
  1. showKeyboard
  2. hideKeyboard
  3. keyboardBuffer

showKeyboard()
Examples
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
showKeyboard()
Related
  1. hideKeyboard
  2. keyboardBuffer

hideKeyboard()
Description

This function disables keyboard input and hides the software keyboard if necessary.

Syntax
hideKeyboard()
Related
  1. showKeyboard
  2. keyboardBuffer

keyboardBuffer()
Examples
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
buffer = keyboardBuffer()
Returns

Contents of keyboard buffer as a string

Related
  1. showKeyboard
  2. hideKeyboard

BACKSPACE
Examples
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
BACKSPACE
Related
  1. keyboardOverview
  2. 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
startRecording()
Related
  1. stopRecording
  2. 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
stopRecording()
Related
  1. startRecording
  2. isRecording

isRecording()
Description

Use this function to programatically determine whether Codea is currently recording the screen.

Syntax
isRecording()
Returns

Boolean, whether Codea is recording the screen

Related
  1. startRecording
  2. stopRecording

backingMode( MODE )
Examples
function setup()
    --Use a standard backing mode (default)
    backingMode( STANDARD )
end
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
backingMode( STANDARD|RETAINED )
Parameters
NameDescription
modeEither STANDARD or RETAINED
Related
  1. STANDARD
  2. 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
backingMode( RETAINED )
Related
  1. backingMode
  2. STANDARD

close()
Examples
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
close()
Related
  1. displayMode
  2. FULLSCREEN_NO_BUTTONS

Vector

Vector and Matrix Types


vec2
Examples
--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
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
NameDescription
xfloat, the x component of this vec2
yfloat, the y component of this vec2
Related
  1. vec2.dot
  2. vec2.normalize
  3. vec2.dist
  4. vec2.distSqr
  5. vec2.len
  6. vec2.lenSqr
  7. vec2.cross
  8. vec2.rotate
  9. vec2.rotate90
  10. vec2.angleBetween

vec2.dot( v )
Description

This method returns the scalar dot product between two vec2 types

Syntax
v1 = vec2( 1, 1 )
x = v1:dot( v )
Parameters
NameDescription
vcompute the dot product with this vec2 and v
Returns

Dot product between this vec2 and v

Related
  1. vec2

vec2.normalize()
Description

This method returns a normalized version of the vector

Syntax
v1 = vec2( 5, 5 )
v1 = v1:normalize()
Returns

Normalized version of this vec2

Related
  1. vec2

vec2.dist( v )
Description

This method returns the distance between two vec2 types

Syntax
v1 = vec2( 1, 1 )
x = v1:dist( vec2(2, 2) )
Parameters
NameDescription
vcompute the distance between this vec2 and v
Returns

Distance between this vec2 and v

Related
  1. vec2

vec2.distSqr( v )
Description

This method returns the squared distance between two vec2 types

Syntax
v1 = vec2( 1, 1 )
x = v1:distSqr( vec2(2, 2) )
Parameters
NameDescription
vcompute the squared distance between this vec2 and v
Returns

Squared distance between this vec2 and v

Related
  1. vec2

vec2.len()
Description

This method returns the length of a vec2

Syntax
v1 = vec2( 2, 1 )
x = v1:len()
Returns

Length of this vec2

Related
  1. vec2

vec2.lenSqr()
Description

This method returns the squared length of a vec2

Syntax
v1 = vec2( 2, 1 )
x = v1:lenSqr()
Returns

Squared length of this vec2

Related
  1. vec2

vec2.cross( v )
Description

This method returns the cross product between two vec2 types

Syntax
v1 = vec2( 1, 1 )
v2 = v1:cross( vec2(2, 2) )
Parameters
NameDescription
vcompute the cross product of this vec2 and v
Returns

Cross product of this vec2 and v

Related
  1. vec2

vec2.rotate( angle )
Description

This method returns a rotated copy of a vec2 type. The angle is assumed to be radians.

Syntax
v1 = vec2( 1, 1 )
v1 = v1:rotate( math.rad(45) )
Parameters
NameDescription
anglefloat, rotate this vector by angle in radians
Returns

Rotated version of this vec2

Related
  1. vec2

vec2.rotate90()
Description

This method returns a copy of a vec2 type, rotated 90 degrees.

Syntax
v1 = vec2( 1, 1 )
v1 = v1:rotate90()
Returns

Rotated version of this vec2

Related
  1. vec2

vec2.angleBetween( v )
Description

This method returns the angle between this vec2 and v in radians.

Syntax
v1 = vec2( 1, 1 )
angle = math.deg( v1:angleBetween( vec2(5, 2) ) )
Parameters
NameDescription
vcompute the angle between this vec2 and v
Returns

Angle between vec2 and v in radians

Related
  1. 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
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
NameDescription
xfloat, x dimension of this vector
yfloat, y dimension of this vector
zfloat, z dimension of this vector
Related
  1. vec3.dot
  2. vec3.normalize
  3. vec3.dist
  4. vec3.distSqr
  5. vec3.len
  6. vec3.lenSqr
  7. vec3.cross

vec3.dot( v )
Description

This method returns the scalar dot product between two vec3 types

Syntax
v1 = vec3( 1, 1, 1 )
x = v1:dot( v )
Parameters
NameDescription
vcompute the dot product with this vec3 and v
Returns

Dot product between this vec3 and v

Related
  1. vec3

vec3.normalize()
Description

This method returns a normalized version of the vector

Syntax
v1 = vec3( 5, 5, 5 )
v1 = v1:normalize()
Returns

Normalized version of this vec3

Related
  1. vec3

vec3.dist( v )
Description

This method returns the distance between two vec3 types

Syntax
v1 = vec3( 1, 1, 1 )
x = v1:dist( vec3(2, 2, 2) )
Parameters
NameDescription
vcompute the distance between this vec3 and v
Returns

Distance between this vec3 and v

Related
  1. vec3

vec3.distSqr( v )
Description

This method returns the squared distance between two vec3 types

Syntax
v1 = vec3( 1, 1, 1 )
x = v1:distSqr( vec3(2, 2, 2) )
Parameters
NameDescription
vcompute the squared distance between this vec3 and v
Returns

Squared distance between this vec3 and v

Related
  1. vec3

vec3.len()
Description

This method returns the length of a vec3

Syntax
v1 = vec3( 2, 1, 0 )
x = v1:len()
Returns

Length of this vec3

Related
  1. vec3

vec3.lenSqr()
Description

This method returns the squared length of a vec3

Syntax
v1 = vec3( 2, 1, 0 )
x = v1:lenSqr()
Returns

Squared length of this vec3

Related
  1. vec3

vec3.cross( v )
Description

This method returns the cross product between two vec3 types

Syntax
v1 = vec3( 1, 1 )
v2 = v1:cross( vec3(2, 2) )
Parameters
NameDescription
vcompute the cross product of this vec3 and v
Returns

Cross product of this vec3 and v

Related
  1. vec3

matrix
Examples
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
matrix[1] … matrix[16]
m = matrix()
m = matrix(1, 2, 3, …. 16)
m = matrix1 * matrix2
Parameters
NameDescription
elementfloat, an element of the matrix
Returns

A new matrix with the given elements

Related
  1. modelMatrix
  2. matrix.rotate
  3. matrix.translate
  4. matrix.scale
  5. matrix.inverse
  6. matrix.transpose
  7. matrix.determinant

matrix.rotate( m, r, x, y, z )
Examples
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
rotated = m:rotate( angle, axisX, axisY, axisZ )
Parameters
NameDescription
anglefloat, the rotation in degrees
axisXfloat, the x component of the axis of rotation
axisYfloat, the y component of the axis of rotation
axisZfloat, the z component of the axis of rotation
Returns

A matrix which rotates m by the specified rotation

Related
  1. matrix

matrix.translate( m, x, y, z )
Examples
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
translated = m:translate( x, y, z )
Parameters
NameDescription
xfloat, the x component of translation
yfloat, the y component of translation
zfloat, optional, defaults to 0 – the z component of translation
Returns

A matrix which translates m by the specified amount

Related
  1. matrix

matrix.scale( m, x, y, z )
Examples
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
scaled = m:scale( x, y, z )
Parameters
NameDescription
xfloat, the x component of scale, or the uniform scale if no other components are given
yfloat, optional, the y component of scale
zfloat, 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
  1. 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
inv = m:inverse()
Parameters
NameDescription
mthe matrix to invert
Returns

A matrix which inverts m

Related
  1. 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
transposed = m:transpose()
Parameters
NameDescription
mthe matrix to transpose
Returns

A matrix which is the transpose of m

Related
  1. 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
det = m:determinant()
Returns

A float equal to the determinant of m

Related
  1. 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
Gravity
Gravity.x
Gravity.y
Gravity.z
Parameters
NameDescription
xfloat, the amount of gravity in the x direction
yfloat, the amount of gravity in the y direction
zfloat, the amount of gravity in the z direction
Related
  1. vec3
  2. 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
UserAcceleration
UserAcceleration.x
UserAcceleration.y
UserAcceleration.z
Parameters
NameDescription
xfloat, the amount of acceleration in the x direction
yfloat, the amount of acceleration in the y direction
zfloat, the amount of acceleration in the z direction
Related
  1. vec3
  2. Gravity

Network

Network Connections and Requests


openURL( url )
Examples
function touched(touch)
    openURL( 'http://twolivesleft.com' )
end
Description

This function opens the URL specified by url in an external browser.

Syntax
openURL( url )
Parameters
NameDescription
urlstring, 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.


-- Success function format
function success( response string or image,
                  statusCode,
                  responseHeaders )


-- Failure function format
function fail( error )
Related
  1. http.get
  2. image

http.get( url, successFunction )
Examples
-- 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
-- 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
http.get( url, successFunction )
http.get( url, successFunction, failFunction )
http.get( url, success, fail, parameterTable )
Parameters
NameDescription
urlstring, the url to submit the request
successFunctionfunction, the function to be called when the request succeeds. This function will be called with an argument representing the returned data.
failFunctionfunction, the function to be called when the request fails. This function will be called with a string argument containing the error.
parameterTabletable, specifying advanced parameters
"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
  1. httpCallbackOverview
  2. image

Storage

Storing Persistent Data


readImage( spriteKey )
Examples
-- 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
readImage( spriteKey )
Parameters
NameDescription
spriteKeystring, 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
  1. saveImage
  2. image

saveImage( spriteKey, image )
Examples
-- 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
saveImage( spriteKey, image )
Parameters
NameDescription
spriteKeystring, name of sprite pack and sprite, separated by a colon (e.g., "Documents:MySprite")
imageimage, the image to be saved under spriteKey
Related
  1. readImage
  2. image

readLocalData( key )
Examples
-- 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
readLocalData( key )
readLocalData( key, defaultValue )
Parameters
NameDescription
keystring, name of the piece of data you would like to get
defaultValueif 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
  1. saveLocalData
  2. clearLocalData

saveLocalData( key, value )
Examples
-- 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
saveLocalData( key, value )
Parameters
NameDescription
keystring, name of the piece of data you would like to store
valuethe value to store under key
Related
  1. readLocalData
  2. 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
clearLocalData( )
Related
  1. readLocalData
  2. 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
readProjectData( key )
readProjectData( key, defaultValue )
Parameters
NameDescription
keystring, name of the piece of data you would like to get
defaultValueif 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
  1. saveProjectData
  2. 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
saveProjectData( key, value )
Parameters
NameDescription
keystring, name of the piece of data you would like to store
valuethe value to store under key
Related
  1. readProjectData
  2. 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
saveProjectInfo( key, value )
Parameters
NameDescription
keystring, name of the project metadata to store. Currently supports "Description" and "Author"
valuethe value to store under key
Related
  1. readProjectInfo

readProjectInfo( key )
Description

This function reads a value associated with key from the project metadata for the current project.

Syntax
readProjectInfo( key )
Parameters
NameDescription
keystring, 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
  1. 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
clearProjectData( )
Related
  1. readProjectData
  2. 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
readGlobalData( key )
readGlobalData( key, defaultValue )
Parameters
NameDescription
keystring, name of the piece of data you would like to get
defaultValueif 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
  1. saveGlobalData
  2. 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
saveGlobalData( key, value )
Parameters
NameDescription
keystring, name of the piece of data you would like to store
valuethe value to store under key
Related
  1. readGlobalData

Updated