Skip to content

Instantly share code, notes, and snippets.

@simsaens
Last active October 1, 2025 13:46
Show Gist options
  • Select an option

  • Save simsaens/a6a4a05d4045069e0132951abd541112 to your computer and use it in GitHub Desktop.

Select an option

Save simsaens/a6a4a05d4045069e0132951abd541112 to your computer and use it in GitHub Desktop.
Codea Runtime Documentation (1 Oct 2025)

Codea API

Gravity (const)

ID: Gravity
Group: Detecting Motion

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

  • x — float, the amount of gravity in the x direction
  • y — float, the amount of gravity in the y direction
  • z — float, the amount of gravity in the z direction

Related: vec3, UserAcceleration

UserAcceleration (const)

ID: UserAcceleration
Group: Detecting Motion

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

  • x — float, the amount of acceleration in the x direction
  • y — float, the amount of acceleration in the y direction
  • z — float, the amount of acceleration in the z direction

Related: vec3, Gravity

RotationRate (const)

ID: RotationRate
Group: Detecting Motion

This global variable represents the rotation rate of the device around three axes. Internally, this makes use of the device gyroscope (if available). On devices where a gyroscope is not available, RotationRate is a zero vector.

Syntax

RotationRate
RotationRate.x
RotationRate.y
RotationRate.z

Parameters

  • x — float, the amount of rotation around the x axis
  • y — float, the amount of rotation around the y axis
  • z — float, the amount of rotation around the z axis

Related: vec3, Gravity

location.enable() (function)

ID: location.enable
Group: Location

Calling this function requests that the device should begin monitoring its physical location. You must call this before you can reliably read location data. Upon first activation the device will request permission to access its location, permission must be granted in order to use location functions. Location updates are disabled by default.

Syntax

location.enable()

Examples

function setup()
    -- enable location updating
    location.enable()

    print(location)
end

Related: location.disable, location.available

location.disable() (function)

ID: location.disable
Group: Location

Calling this function requests that the device should stop monitoring its physical location. Disabling location updates preserves battery power.

Syntax

location.disable()

Related: location.enable, location.available

location.available() (function)

ID: location.available
Group: Location

This function returns whether location data is available. If location updating has not been enabled, or is not permitted, this function will return false.

Syntax

location.available()

Returns

A boolean value specifying whether location data is available

Related: location.enable, location.disable

location.distanceTo(lat, lon) (function)

ID: location.distanceTo
Group: Location

This function returns the distance in meters from the current location (if available) to the specified latitude and longitude.

Syntax

location.distanceTo(lat, lon)

Returns

Distance in meters between the current location and specified coordinates

Related: location.distanceBetween

location.distanceBetween(lat1,lon1,lat2,lon2) (function)

ID: location.distanceBetween
Group: Location

This function returns the distance in meters between two locations specified by the coordinates lat1, lon1, lat2, lon2.

Syntax

location.distanceBetween(lat1, lon1, lat2, lon2)

Returns

Distance in meters between the two specified coordinates

Related: location.distanceTo

location.latitude (const)

ID: location.latitude
Group: Location

This value specifies the current latitude if location is available.

Syntax

location.latitude

Returns

Current latitude, if available. Nil if not.

Related: location.longitude, location.enable

location.longitude (const)

ID: location.longitude
Group: Location

This value specifies the current longitude if location is available.

Syntax

location.longitude

Returns

Current longitude, if available. Nil if not.

Related: location.latitude, location.enable

location.altitude (const)

ID: location.altitude
Group: Location

This value specifies the current altitude if location is available. Positive values indicate altitudes above sea level. Negative values indicate altitudes below sea level.

Syntax

location.altitude

Returns

Current altitude, if available. Nil if not.

Related: location.enable

location.horizontalAccuracy (const)

ID: location.horizontalAccuracy
Group: Location

This value specifies the horizontal accuracy of the latitude and longitude of the current location. This value indicates the radius of the circle in which the latitude and longitude are at the center.

A negative value indicates that the location’s latitude and longitude are invalid.

Syntax

location.horizontalAccuracy

Returns

Current horizontal accuracy, if available. Nil if not.

Related: location.latitude, location.longitude

location.verticalAccuracy (const)

ID: location.verticalAccuracy
Group: Location

This value specifies the accuracy of the altitude of the current location. The altitude value could be plus or minus this value.

A negative value indicates that the current altitude is invalid.

Syntax

location.verticalAccuracy

Returns

Current vertical accuracy, if available. Nil if not.

Related: location.altitude

location.speed (const)

ID: location.speed
Group: Location

This value specifies the current speed of the device in meters per second. A negative value indicates an invalid speed.

Syntax

location.speed

Returns

Current speed, if available. Nil if not.

Related: location.course

location.course (const)

ID: location.course
Group: Location

This variable specifies the current heading of the device measured in degrees starting at due north and moving clockwise around the compass. A negative value indicates an invalid direction.

Syntax

location.course

Returns

Current course, if available. Nil if not.

Related: location.speed

tween(time, subject, target) (function)

ID: tweenCall
Group: Animating Values

Animates values in subject until they are equal to the key value pairs specified the table target over time seconds. The optional easing type and callback can also be specified.

callback is a function that will be called when the tween has finished animating. Any additional parameters passed to tween are forwarded to the callback function as additional arguments.

tween returns a table that can be used as a unique identifier to identify the tween. This table can be passed to tween.stop, tween.reset and tween.play. Note that tweens play by default upon initialization.

Note that the easing parameter may be passed in place of the options table, this will assume the default loop type of tween.loop.once. If you would like to specify a custom loop type, then pass a table for options with the keys 'loop' and 'easing' set to the desired values.

Syntax

tween( time, subject, target )

tween( time, subject, target, easing )

tween( time, subject, target, easing,
                      callback )

tween( time, subject, target, options,
                      callback )

tween( time, subject, target, options,
                      callback, ... )

tween( time, subject, target, options,
                      callback, ... )

Parameters

  • time — float, the duration of the tween in seconds.
  • subject — table or userdata, the object to animate.
  • target — table, a table of key-value pairs that will be animated in subject, i.e. {x = 10} will animate x to the value 10 in subject.
  • easing — string or function, an optional easing type for the tween which can be specified as a function or string. There is a complete set of easing functions that fall into the general categories:

linear The default easing function quad, cubic, quart, quint, expo, sine Different variations of smooth acceleration and deceleration back Causes the subject to overshoot and then pull back bounce Causes the subject to hit the target and bounce several times elastic Causes the subject to oscillate like a guitar string around the target

Each easing curve has four variants with the exception of linear

in out inOut outIn

Easing functions a combination of type and variant, such as 'elasticIn', 'quadInOut' and 'backOut'.

These easing functions were adapted from Emmanuel Oga’s easing library

  • options — table, may contain a loop type specified under the 'loop' key and an easing type specified under the 'easing' key
  • callback — function, a function to call when this tween has completed

Returns

table, returns a tween identifier that can be used to stop, reset or play the tween

Examples

box = { x = 10, y = 10,
        width = 20, height = 20,
        fillColor = color(255) }

tween(1, box, {x = 100, y = 100})

tween(1, box,
        {fillColor = color(255,0,0)})

tween(1, box, {x = 100, y = 100},
         tween.easing.quadIn)

tween(1, box, {x = 100, y = 100},
              tween.easing.linear)

tween(1, box, {x = 100, y = 100},
              tween.easing.linear,
              function()
                print("Tween Ended")
              end)

tween(1, box, {x = 100, y = 100},
              tween.easing.linear,
              function(param)
                  print(param)
              end, "Tween Ended")

Related: tween.stop, tween.stopAll, tween.reset, tween.resetAll, tweem.play

tween.stop(id) (function)

ID: tween.stop
Group: Animating Values

Stops the tween specified by id. This does not reset the subject's values to their initial state.

Syntax

tween.stop( id )

Parameters

  • id — table, the id of the tween to stop

Examples

point = { x = 10, y = 10}
id = tween(1, point, {x = 100})
tween.stop(id)

Related: tween.stop, tween.stopAll, tween.reset, tween.resetAll

tween.stopAll() (function)

ID: tween.stopAll
Group: Animating Values

Stops all active tweens without resetting them.

Syntax

tween.stopAll()

Examples

point = { x = 10, y = 10}
tween(1, point, {x = 100})
tween(2, point, {x = 200})

-- all tweens will now cease animating
tween.stopAll()

Related: tween.stop, tween.stopAll, tween.reset, tween.resetAll

tween.reset(id) (function)

ID: tween.reset
Group: Animating Values

Stops the tween specified by id and resets the subject's values to their initial state.

Syntax

tween.reset( id )

Parameters

  • id — table, the id of the tween to reset

Examples

point = { x = 10, y = 10}
id = tween(1, point, {x = 100})
-- point.x will now now return to 10
tween.reset(id)

Related: tween.stop, tween.stopAll, tween.reset, tween.resetAll

tween.resetAll() (function)

ID: tween.resetAll
Group: Animating Values

Resets all active tweens, returning all subject's to their state before the animation.

Syntax

tween.resetAll()

Examples

point = { x = 10, y = 10}
tween(1, point, {x = 100})
tween(2, point, {x = 200})

-- point will now return to {x = 10, y = 10}
tween.resetAll()

Related: tween.stop, tween.stopAll, tween.reset, tween.resetAll

tween.play(id) (function)

ID: tween.play
Group: Animating Values

Plays the tween specified by id. This does not reset the subject's values to their initial state.

Syntax

tween.play( id )

Parameters

  • id — table, the id of the tween to play

Examples

point = { x = 10, y = 10}
id = tween(1, point, {x = 100})

function pauseTween(id)
  tween.stop(id)
end

function resumeTween(id)
  tween.play(id)
end

Related: tween.stop, tween.stopAll, tween.reset, tween.resetAll

tween.delay(duration, callback) (function)

ID: tween.delay
Group: Animating Values

This function creates a tween that simply waits for the specified duration. You might use this to create a pause within a tween.sequence, or to delay the calling of a particular function.

Any additional arguments specified after the callback parameter will be passed as arguments to the callback function.

Syntax

tween.delay( duration )
tween.delay( duration, callback )
tween.delay( duration, callback, ... )

Parameters

  • duration — number, the duration of the delay
  • callback — function, optional callback function

Returns

table, returns the tween identifier for the delay

Examples

point = {x = 10, y = 10}

t1 = tween(1, point, {x = 100})

-- Create a delay
delay = tween.delay(1.0)

t2 = tween(1, point, {y = 150})

tween.sequence( t1, delay, t2 )

Related: tween, tween.sequence

tween.sequence( t1, t2, ... ) (function)

ID: tween.sequence
Group: Animating Values

This function allows you to compose sequences made up of multiple tweens. Each call to the tween function returns an id, tween.sequence accepts a list of these ids and plays them back one after the other.

Syntax

tween.sequence( t1, t2, t3, ... )

Parameters

  • t1 — the id of a tween in the sequence

Returns

table, returns the tween identifier for the first tween in the sequence

Examples

point = {x = 10, y = 10}
t1 = tween(1, point, {x = 100})
t2 = tween(1, point, {x = 50})
t3 = tween(1, point, {y = 150})
tween.sequence( t1, t2, t3 )

Related: tween, tween.path, tween.resetAll

tween.path( time, subject, targets ) (function)

ID: tween.path
Group: Animating Values

tween.path is similar to tween except it accepts an array of target values. The resulting animation interpolates across all the values in targets using a spline.

Syntax

tween.path( time, subject, targets )

tween.path( time, subject,
            targets, easing )

tween.path( time, subject,
            targets, options )

tween.path( time, subject,
            targets, options, callback )

tween.path( time, subject,
            targets, options,
            callback, ... )

Parameters

  • time — float, the duration of the tween
  • subject — table or userdata, the object to animate
  • targets — table, an array of tables containing key-value pairs for each point along the path
  • options — table, may contain a loop type specified under the 'loop' key and an easing type specified under the 'easing' key
  • easing — function, one of the easing functions specified in tween.easing
  • callback — function, triggered when the animation is complete

Returns

table, returns a tween identifier that can be used to pause, reset or stop the tween

Examples

point = {x = 10, y = 10}

p1 = {x = 10, y = 10}
p2 = {x = 100, y = 10}
p3 = {x = 100, y = 100}
p4 = {x = 10, y = 100 }

tween.path( 4.0, point, {p1,p2,p3,p4,p1} )

Related: tween

tween.loop.once (const)

ID: tween.loop.once
Group: Looping Types

Plays the tween once. This is the default loop type.

Syntax

tween.loop.once

Related: tween

tween.loop.forever (const)

ID: tween.loop.forever
Group: Looping Types

Plays the tween over and over again, restarting it each time.

Syntax

tween.loop.forever

Related: tween

tween.loop.pingpong (const)

ID: tween.loop.pingpong
Group: Looping Types

Plays the tween backwards after it finishes, and then continues to repeat it back and forth.

Syntax

tween.loop.pingpong

Related: tween

tween.easing.linear (const)

ID: tween.easing.linear
Group: Easing Types

Syntax

tween.easing.linear

Related: tween

tween.easing.quadIn (const)

ID: tween.easing.quadIn
Group: Easing Types

Syntax

tween.easing.quadIn

Related: tween

tween.easing.quadOut (const)

ID: tween.easing.quadOut
Group: Easing Types

Syntax

tween.easing.quadOut

Related: tween

tween.easing.quadInOut (const)

ID: tween.easing.quadInOut
Group: Easing Types

Syntax

tween.easing.quadInOut

Related: tween

tween.easing.quadOutIn (const)

ID: tween.easing.quadOutIn
Group: Easing Types

Syntax

tween.easing.quadOutIn

Related: tween

tween.easing.cubicIn (const)

ID: tween.easing.cubicIn
Group: Easing Types

Syntax

tween.easing.cubicIn

Related: tween

tween.easing.cubicOut (const)

ID: tween.easing.cubicOut
Group: Easing Types

Syntax

tween.easing.cubicOut

Related: tween

tween.easing.cubicInOut (const)

ID: tween.easing.cubicInOut
Group: Easing Types

Syntax

tween.easing.cubicInOut

Related: tween

tween.easing.cubicOutIn (const)

ID: tween.easing.cubicOutIn
Group: Easing Types

Syntax

tween.easing.cubicOutIn

Related: tween

tween.easing.quartIn (const)

ID: tween.easing.quartIn
Group: Easing Types

Syntax

tween.easing.quartIn

Related: tween

tween.easing.quartOut (const)

ID: tween.easing.quartOut
Group: Easing Types

Syntax

tween.easing.quartOut

Related: tween

tween.easing.quartInOut (const)

ID: tween.easing.quartInOut
Group: Easing Types

Syntax

tween.easing.quartInOut

Related: tween

tween.easing.quartOutIn (const)

ID: tween.easing.quartOutIn
Group: Easing Types

Syntax

tween.easing.quartOutIn

Related: tween

tween.easing.quintIn (const)

ID: tween.easing.quintIn
Group: Easing Types

Syntax

tween.easing.quintIn

Related: tween

tween.easing.quintOut (const)

ID: tween.easing.quintOut
Group: Easing Types

Syntax

tween.easing.quintOut

Related: tween

tween.easing.quintInOut (const)

ID: tween.easing.quintInOut
Group: Easing Types

Syntax

tween.easing.quintInOut

Related: tween

tween.easing.quintOutIn (const)

ID: tween.easing.quintOutIn
Group: Easing Types

Syntax

tween.easing.quintOutIn

Related: tween

tween.easing.expoIn (const)

ID: tween.easing.expoIn
Group: Easing Types

Syntax

tween.easing.expoIn

Related: tween

tween.easing.expoOut (const)

ID: tween.easing.expoOut
Group: Easing Types

Syntax

tween.easing.expoOut

Related: tween

tween.easing.expoInOut (const)

ID: tween.easing.expoInOut
Group: Easing Types

Syntax

tween.easing.expoInOut

Related: tween

tween.easing.expoOutIn (const)

ID: tween.easing.expoOutIn
Group: Easing Types

Syntax

tween.easing.expoOutIn

Related: tween

tween.easing.sineIn (const)

ID: tween.easing.sineIn
Group: Easing Types

Syntax

tween.easing.sineIn

Related: tween

tween.easing.sineOut (const)

ID: tween.easing.sineOut
Group: Easing Types

Syntax

tween.easing.sineOut

Related: tween

tween.easing.sineInOut (const)

ID: tween.easing.sineInOut
Group: Easing Types

Syntax

tween.easing.sineInOut

Related: tween

tween.easing.sineOutIn (const)

ID: tween.easing.sineOutIn
Group: Easing Types

Syntax

tween.easing.sineOutIn

Related: tween

tween.easing.backIn (const)

ID: tween.easing.backIn
Group: Easing Types

Syntax

tween.easing.backIn

Related: tween

tween.easing.backOut (const)

ID: tween.easing.backOut
Group: Easing Types

Syntax

tween.easing.backOut

Related: tween

tween.easing.backInOut (const)

ID: tween.easing.backInOut
Group: Easing Types

Syntax

tween.easing.backInOut

Related: tween

tween.easing.backOutIn (const)

ID: tween.easing.backOutIn
Group: Easing Types

Syntax

tween.easing.backOutIn

Related: tween

tween.easing.bounceIn (const)

ID: tween.easing.bounceIn
Group: Easing Types

Syntax

tween.easing.bounceIn

Related: tween

tween.easing.bounceOut (const)

ID: tween.easing.bounceOut
Group: Easing Types

Syntax

tween.easing.bounceOut

Related: tween

tween.easing.bounceInOut (const)

ID: tween.easing.bounceInOut
Group: Easing Types

Syntax

tween.easing.bounceInOut

Related: tween

tween.easing.bounceOutIn (const)

ID: tween.easing.bounceOutIn
Group: Easing Types

Syntax

tween.easing.bounceOutIn

Related: tween

tween.easing.elasticIn (const)

ID: tween.easing.elasticIn
Group: Easing Types

Syntax

tween.easing.elasticIn

Related: tween

tween.easing.elasticOut (const)

ID: tween.easing.elasticOut
Group: Easing Types

Syntax

tween.easing.elasticOut

Related: tween

tween.easing.elasticInOut (const)

ID: tween.easing.elasticInOut
Group: Easing Types

Syntax

tween.easing.elasticInOut

Related: tween

tween.easing.elasticOutIn (const)

ID: tween.easing.elasticOutIn
Group: Easing Types

Syntax

tween.easing.elasticOutIn

Related: tween

Craft (overview)

ID: craftOverview
Group: Overview

Craft provides extended capabilities to Codea that make it much easier to create 3D scenes, physics and game logic. Craft introduces a number of new classes. These include craft.entity, which is the basic building block of 3D scenes.

Several systems are introduced, including: craft.scene - The core class in craft, draws and updates all other objects and systems craft.physics - Physics settings and helper functions craft.voxels - Streaming voxel terrain, block types and helper functions craft.ar - Augmented Reality, world tracking and helper functions

Each system can be used to access built-in objects, change settings or trigger specialised features.

Related: craft.scene, craft.physics, craft.voxels, craft.ar, craft.entity

craft.scene (type)

ID: craft.scene
Group: Entities

In order to use craft you must make a scene. Scenes are used to create, update and draw all entities and components. Scenes also control basic things, such as ambient lighting, fog, the sky and contain references to some built-in entities. Built-in entities include: a main camera that renders the scene by default a 'sun' which is a directional light a 'sky' which is a renderer with a Materials:Skybox material used to draw the background

Syntax

scene = craft.scene()

Parameters

  • main — scene [static], the main scene which when set will automatically update and draw each frame
  • camera — entity, the main camera entity (contains a camera component)
  • sun — entity, the sun entity (contains a directional light component)
  • sky — sky, the sky entity (contains a renderer with a Skybox material)
  • ambientColor — color, the ambient light color (for materials with lighting)
  • fogEnabled — bool, turns fog on and off
  • fogNear — number, the distance where fog begins
  • fogFar — number, the distance where fog reaches maximum density
  • fogColor — color, the color of the fog
  • renderBatchCount — int, the current number of batches being rendered (the less the better performance you can expect)
  • renderBatchCullCount — int, the current number of batches saved by frustum culling

Examples

function setup()
	-- Create the scene
	scene = craft.scene()

  -- Move the main camera
  scene.camera.position = vec3(0, -10, 0)

  -- Adjust the scene lighting
  scene.sun.rotation = quat.eulerAngles(45,0,45)
  scene.ambientColor = color(90,90,90)

  -- Turn on fog and set distances and color
  scene.fogEnabled = true
  scene.fogNear = 10
  scene.fogFar = 50
  scene.fogColor = color(255,255,255)

  -- Get the sky material and change the sky and horizon colors
  local skyMaterial = scene.sky.material
  skyMaterial.sky = color(255,100,150)
  skyMaterial.horizon = color(0,0,0)

  -- Set the main scene to draw and update it automatically
  craft.scene.main = scene
end

Related: craft.renderer, craft.camera

craft.entity (type)

ID: craft.entity
Group: Entities

Entities are flexible objects that can be customised to change their appearance and behaviour. You can customise an entity by adding components. Each type of component serves a different purpose. Renderer components change entity appearance, physics components give entities physical behaviour.

Syntax

myEntity = scene:entity()

Parameters

  • model — model, the model used for drawing this entity (stored within the attached renderer component)
  • material — material, the material used for drawing this entity (stored within the attached renderer component)
  • position — vec3, the position of this entity in local coordinate space
  • worldPosition — vec3, the position of this entity in world coordinate space
  • rotation — quat, the rotation of this entity in local coordinate space
  • worldRotation — quat, the rotation of this entity in world coordinate space
  • scale — vec3, the scale of this entity in local coordinate space
  • x — float, the x position of this entity in local coordinate space
  • y — float, the y position of this entity in local coordinate space
  • z — float, the z position of this entity in local coordinate space
  • eulerAngles — vec3, the rotation of this entity in local coordinate space expressed in euler angles
  • parent — entity, the parent of this entity (in the transform hierarchy)
  • children — table [readonly], an array of children entities attached to this entity
  • active — bool, turn on and off to enable and disable entity in the scene

Examples

scene = craft.scene()

-- Create a new entity
entity = scene:entity()

-- Attach a model and material for rendering
entity.model = craft.model.cube(vec3(1,1,1))
entity.material = craft.material(asset.builtin.Materials.Standard)

-- Rotate the entity
entity.eulerAngles = vec3(45, 0, 45)

-- Set the z position of the entity
entity.z = -10

-- Destroy the entity
entity:destroy()

Related: craft.renderer

entity.add( type, ... ) (method)

ID: entity.add
Group: Entities

Adds a component to this entity. There are several built-in components that can be added, such as craft.renderer, craft.shape.box and others. Lua classes can also be added as a component. Any additional parameters beyond the type will be forwarded to the component itself. For Lua classes the first parameter passed to the init() function will be the entity itself (followed by the rest of the arguments) allowing it to be stored for later use. Some special callback methods can be implemented in Lua classes to provide extra functionality.

The update() method will be called once per frame (useful for animations and game logic). The fixedUpdate() method will be called once per physics update (useful for physics related behaviour).

If the component is successfully added, the component will be returned. Only one of a given component type can be added at a time.

Syntax

myEntity:add( craft.renderer, myModel )
myEntity:add( craft.shape.box, vec3(1,1,1) )
myEntity:add( LuaClass, p1, p2, p3, ... )

Parameters

  • type — type, the type of component to add to this entity

Returns

object, the component added to this entity

Examples

-- Lua classes can be attached to entities to customise behaviour
Mover = class()

function Mover:init(entity, speed)
    self.entity = entity
    self.speed = speed
end

function Mover:update()
    -- Move the entity to the right at speed meters per second
    self.entity.x = self.entity.x + self.speed * DeltaTime
    self.entity.eulerAngles = vec3(0, ElapsedTime * 90, 270)
end

function setup()
  -- Create a new craft scene
  scene = craft.scene()

    -- Create an entity and attach a Mover to make it move automatically
    local entity = scene:entity()

    entity.model = craft.model("SpaceKit:spaceCraft6")
    entity.scale = vec3(0.1, 0.1, 0.1)
    entity.x = -10

    entity:add(Mover, 1.5)

    scene.camera.z = 20
    scene.camera.eulerAngles = vec3(0,0,180)
end

function update(dt)
  scene:update(dt)
end

function draw()
  update(DeltaTime)
  scene:draw()
end

Related: craft.entity

entity.get( type ) (method)

ID: entity.get
Group: Entities

Gets a component of a particular type attached to this entity. If the component does not exist, nil is returned.

Syntax

myEntity:get( craft.renderer )
myEntity:get( craft.shape.box )
myEntity:get( craft.rigidbody )
myEntity:get( LuaClass )

Parameters

  • type — type, the type of component to get from this entity

Returns

object, the requested component (or nil if it does not exist)

Related: craft.entity, entity.add, entity.remove

entity.remove( componentType ) (method)

ID: entity.remove
Group: Entities

Removes a component of a particular type attached to this entity, if it exists.

Syntax

myEntity:remove( craft.renderer )
myEntity:remove( craft.shape.box )
myEntity:get( craft.rigidbody )
myEntity:remove( LuaClass )

Parameters

  • type — type, the type of component to remove from this entity

Related: craft.entity, entity.add, entity.remove

entity.destroy() (method)

ID: entity.destroy
Group: Entities

Marks this entity for destruction in the next frame. Any children will also be marked for destruction.

Syntax

myEntity:destroy()

Related: craft.entity

entity.transformPoint() (method)

ID: entity.transformPoint
Group: Entities

Transforms a point from local space into world space using this entity's transform.

Syntax

myEntity:transformPoint(point)

Parameters

  • point — vec3, the point to transform

Returns

vec3, the transformed point

Related: craft.entity

entity.inverseTransformPoint() (method)

ID: entity.inverseTransformPoint
Group: Entities

Transforms a point from world space into local space using this entity's transform.

Syntax

myEntity:inverseTransformPoint(point)

Parameters

  • point — vec3, the point to transform

Returns

vec3, the transformed point

Related: craft.entity

entity.transformDirection() (method)

ID: entity.transformDirection
Group: Entities

Transforms a direction from local space into world space using this entity's transform.

Syntax

myEntity:transformDirection(point)

Parameters

  • direction — vec3, the direction to transform

Returns

vec3, the transformed direction

Related: craft.entity

entity.inverseTransformDirection() (method)

ID: entity.inverseTransformDirection
Group: Entities

Transforms a direction from world space into local space using this entity's transform.

Syntax

myEntity:inverseTransformDirection(direction)

Parameters

  • direction — vec3, the direction to transform

Related: craft.entity

craft.camera (type)

ID: craft.camera
Group: Rendering

A component used to draw the scene from its point of view.

Syntax

myEntity:add(craft.camera, fov, nearPlane, farPlane, false)
myEntity:add(craft.camera, orthoSize, nearPlane, farPlane, true)

Parameters

  • fieldOfView — float, the field of view of the camera in degrees
  • ortho — bool, orthographic rendering mode for this camera
  • nearPlane — float, the near plane for the camera (the closest thing that can be rendered)
  • farPlane — float, the far plane for the camera (the farthest thing that can be rendered)
  • clearDepthEnabled — bool, the depth clearing flag for the camera (when set to true the existing depth buffer will be cleared before rendering)
  • clearColorEnabled — bool, the color clearing flag for the camera (when set to true the existing color buffer will be cleared before rendering)
  • clearColor — color, the color to use when clearing the color buffer before rendering with the camera
  • entity — entity, the entity that the camera is attached to

Examples

-- create a new entity and add a camera to it
camera = scene:entity():add(craft.camera, 45, 0.1, 1000, false)

Related: craft.entity

camera.screenToWorld( position ) (method)

ID: camera.screenToWorld
Group: Rendering

Converts a position given in screen coordinates (x, y) and a depth value (z) to world space relative to this camera.

Syntax

myCamera:screenToWorld( position )

Parameters

  • position — vec3, the position to convert to world space

Returns

vec3

Related: craft.camera

camera.screenToRay( position ) (method)

ID: camera.screenToRay
Group: Rendering

Converts a position in screen coordinates (x, y) to a ray in the form of an origin and direction relative to this camera.

Syntax

origin, dir = myCamera:screenToRay( position )

Parameters

  • position — vec2, the position to generate a ray with

Returns

vec3, vec3

Related: craft.camera

camera.worldToScreen( screenPos ) (method)

ID: camera.worldToScreen
Group: Rendering

Converts a position given in world coordinates to screen coordinates relative to this camera.

Syntax

myCamera:worldToScreen( screenPos )

Parameters

  • position — vec3, the position to convert to screen space

Returns

vec2

Related: craft.camera

camera.viewport( x, y, width, height ) (method)

ID: camera.viewport
Group: Rendering

Sets or gets the current viewport using normalized coordinates. Can be used for adjusting the rendered area of the camera relative to the screen. For instance, calling camera:viewport(0.0, 0.0, 0.5, 1.0) will render the camera to only the left half of the screen.

Syntax

myCamera:viewport(x, y, width, height)
x, y, w, h = myCamera:viewport()

Parameters

  • x — float, the x position of the viewport
  • y — float, the y position of the viewport
  • width — float, the width viewport
  • height — float, height of the viewport

Returns

x, y, w, h

Related: craft.camera

camera.addPostEffect( postEffect ) (method)

ID: camera.addPostEffect
Group: Rendering

Adds a post processing effect to this camera

Syntax

local bloom = craft.bloomEffect()
myCamera.hdr = true
myCamera:addPostEffect( bloom )

Parameters

  • postEffect — postEffect, the post processing effect to add to this camera

Related: craft.camera

craft.bloomEffect (type)

ID: craft.bloomEffect
Group: Rendering

A post processing effect that can be added to camera components to create a bloom effect Enable camera.hdr when using bloom to allow for intensely bright objects that will interact with the effect

Syntax

local bloom = craft.bloomEffect()
myCamera.hdr = true
myCamera:addPostEffect( bloom )

Parameters

  • enabled — boolean, enables or disables the effect
  • iterations — integer, the number of iterations of blur to apply, more iterations increase the blur
  • threshold — number, the threshold for color intensity before bloom begins to apply
  • softThreshold — number, the soft threshold parameter for adjusting the bloom curve (also known as the knee)
  • intensity — number, the intensity of the bloom effect

Examples

scene = craft.scene()
cam = scene.camera:get(craft.camera)
cam.hdr = true
local bloom = craft.bloomEffect()
cam:addPostEffect( bloom )

Related: craft.entity

craft.renderer (type)

ID: craft.renderer
Group: Rendering

A component used to draw a 3D model in the scene. Renderers can be attached to entities by using entity:add(craft.renderer) or by setting entity.model and entity.material directly.

Syntax

myEntity:add(craft.renderer, model)

Parameters

  • material — material, the material to apply to this renderer
  • model — model, the model to render

Examples

-- create a new entity
entity = scene.entity()
entity.model = craft.model.icosphere(1, 3, false)
entity.material = craft.material(asset.builtin.Materials.Standard)

Related: craft.entity

craft.light (type)

ID: craft.light
Group: Rendering

A component that casts light onto the scene. Different types of lights can be used to achieve different lighting effects, these include: DIRECTIONAL, SPOT and POINT. The position and rotation of the entity controls the position and rotation of the attached light source. By default the scene contains a single directional light known as the sun.

The scene also contains an ambient light controlled by scene.ambientColor. The ambient light term is added to the emission of all other lights and is generally used for simulating scattered environmental light.

Syntax

myEntity:add(craft.light, DIRECTIONAL)
myEntity:add(craft.light, SPOT)
myEntity:add(craft.light, POINT)

Parameters

  • type — the type of light, can be DIRECTIONAL, SPOT, POINT
  • color — color, the color of the light
  • intensity — float, how intense the emitted light is (can be higher than one)
  • distance — float, how far the light can travel (only applies for spot and point lights)
  • angle — float, the spread angle of the light (only applies to spot lights)
  • penumbra — float, the angle where light intensity begins to fade (only applies to spot lights)
  • decay — float, the rate at which the intensity of the light fades due to distance (only applies to spot and point lights)
  • mask — bitmask, the mask for which renderers should be effected by this light source

Examples

-- Create a new entity
entity = scene.entity()
light = entity:add(craft.light, POINT)
light.distance = 10
light.intensity = 1
light.color = color(255,128,128)
entity.position = vec3(0,5,0)

Related: craft.entity, craft.renderer, craft.camera

DIRECTIONAL (const)

ID: DIRECTIONAL
Group: Rendering

This constant specifies the directional light type. Directional lights simulate an infinitely distant light source where all rays are parallel (similar to the sun). The position of a directional light is ignored.

Syntax

DIRECTIONAL

Returns

int

Related: craft.light

SPOT (const)

ID: SPOT
Group: Rendering

This constant specifies the spot light type. Spotlights simulate a cone of light within a specified angle (see the angle property). The distance and decay properties define how far the light travels and how quickly the intensity falls off over distance.

The penumbra property defines how hard the edge of the spotlight is. The closer this value is to angle the harder the edge will appear. Setting this to zero will give the appearance of very soft spotlight.

Syntax

SPOT

Returns

int

Related: craft.light

POINT (const)

ID: POINT
Group: Rendering

This constant specifies the point light type. Point lights simulate a omnidirectional light source emitting from a single point. The distance and decay properties define how far the light travels and how quickly the intensity falls off over distance.

Syntax

POINT

Returns

int

Related: craft.light

craft.material (type)

ID: craft.material
Group: Rendering

This type represents a surface material. Materials are used to control the physical appearance of 3D objects, such as models, sky boxes and voxels.

Set the material property on a craft.renderer component to apply a given material to it. Materials are built out of modular shaders with a set of dynamic properties.

Each named property has a different effect on the material's appearance. For instance, the map property can be set with an image or asset string to change the surface appearance of the Standard material. Other properties can change the normals, roughness, metalness and reflectiveness of materials.

Syntax

myMaterial = craft.material(asset.builtin.Materials.Basic)
myMaterial = craft.material(asset.builtin.Materials.Standard)
myMaterial = craft.material(asset.builtin.Materials.Specular)
myMaterial = craft.material(asset.builtin.Materials.Skybox)

Parameters

  • blendMode — int, the blend mode to use for this material (can be NORMAL, ADDITIVE or MULTIPLY)
  • renderQueue — int, the render queue to use for this material (can be OPAQUE or TRANSPARENT)

Examples

local e = scene:entity()
e.model = craft.cube(vec3(1,1,1))

-- Load the standard material (physically based rendering)
local m = craft.material(asset.builtin.Materials.Standard)
e.material = m

-- Surface color
m.diffuse = color(255, 255, 255)
-- Opacity (0.0 fully transparent, 1.0 fully opaque)
m.opacity = 1.0
-- Surface color texture map
m.map = "Surfaces:Basic Bricks Color"
-- Texture map offset and repeat (tiling)
m.offsetRepeat = vec4(0.0, 0.0, 3.0, 3.0)
-- Normal map for small scale surface details
m.normalMap = "Surfaces:Basic Bricks Normal"
-- How intense the normal map effect is in tangent space (also used for flipping)
m.normalScale = vec2(1, 1)
-- How rough the material is
m.roughness = 1.0
-- A texture that controls the roughness
m.roughnessMap = "Surfaces:Basic Bricks Roughness"
-- How metallic the material is
m.metalness = 1.0
-- A texture that controls how metallic the surface is
m.metalnessMap = nil
-- The environment map (a CubeTexture), specular illumination
m.envMap = nil
-- The ambient occlusion map, used for self-occluding shadows
m.aoMap = "Surfaces:Basic Bricks AO"
-- How intense the aoMap is
m.aoMapIntensity = 2.5
-- The displacement map which modifies vertex positions based on normals
m.displacementMap = nil
-- Base offset of the displacement map
m.displacementBias = 0
-- Scale of the displacement map
m.displacementScale = 1

Related: craft.entity, craft.renderer, craft.model

craft.model (type)

ID: craft.model
Group: Rendering

This type represents a model. Used in conjunction with a craft.renderer component to draw 3D objects.

Existing model assets can be loaded by using craft.model(asset), supported 3D model formats are .obj, .fbx, .stl and .blend.

Models are made up of a number of triangles, which are in-turn made up of vertices. Each vertex has a number of attributes that control their appearance, such as position, color and normal.

To make a triangle you must set the indices of the model using the indices property. You can resize the number of indices and vertices by using the resizeIndices() and resizeVertices() functions.

Syntax

myModel = craft.model()
myModel = craft.model( asset )

Parameters

  • vertexCount — int, the number of vertices in this model
  • indexCount — int, the number of indices in this model
  • positions — array, the positions of the vertices of this model
  • normals — array, the normals of the vertices of this model
  • colors — array, the colors of the vertices of this model
  • uvs — array, the uvs of the vertices of this model
  • indices — array, the primitive indices of this model used to form triangles
  • material — material, the material for this model (overridden by renderer materials)

Examples

-- Create a blank model
m = craft.model()

-- Blank models include attributes for position, normal, color and uv
local positions = {vec3(-1.0,-1.0,0), vec3(-1.0,1.0,0), vec3(1.0,1.0,0), vec3(1.0,-1.0,0)}
local normals = {vec3(0,0,-1), vec3(0,0,-1), vec3(0,0,-1), vec3(0,0,-1)}
local uvs = {vec2(0,0), vec2(0,1), vec2(1,1), vec2(1,0)}
local c = color(245, 3, 3, 255)
local colors = {c, c, c, c}

-- Indices are used to create triangles using groups of 3 vertices
local indices = {3,2,1,4,3,1}

-- Update model vertices using tables
m.positions = positions
m.normals = normals
m.uvs = uvs
m.colors = colors
m.indices = indices

Related: craft.renderer, craft.material

craft.model.cube (function)

ID: craft.model.cube
Group: Rendering

Creates a cube model with the specified size and offset. By default the size parameter is set to (1,1,1), and the offset parameter is (0,0,0).

Syntax

myModel = craft.model.cube()
myModel = craft.model.cube(size)
myModel = craft.model.cube(size, offset)

Parameters

  • size — vec3, the size of the cube
  • offset — vec3, the offset of the center of the cube

craft.model.icosphere (function)

ID: craft.model.icosphere
Group: Rendering

Creates an icosphere model. An icosphere is a geodesic dome made from equally sized triangles. The number of subdivisions specified will control how dense the sphere is (increasing the number of triangles). Setting the icosphere to flat will created faceted faces, otherwise the icosphere will have a smooth appearance.

Syntax

myModel = craft.model.icosphere(radius)
myModel = craft.model.icosphere(radius, subdivisions)
myModel = craft.model.icosphere(radius, subdivisions, flat)

Parameters

  • radius — float, the radius of the icosphere
  • subdivisions — int, the number of subdivisions to apply the base icosphere

craft.model.plane (function)

ID: craft.model.plane
Group: Rendering

Creates a horizontal plane model with the specified size and offset. By default the size parameter is set to (1, 1), and the offset parameter is (0, 0, 0).

Syntax

myModel = craft.model.plane()
myModel = craft.model.plane(size)
myModel = craft.model.plane(size, offset)

Parameters

  • size — vec2, the size of the plane (x, z dimensions)
  • offset — vec3, the offset of the center of the plane

model.resizeVertices( size ) (method)

ID: model.resizeVertices
Group: Rendering

Sets the number of vertices in the model.

Syntax

myModel:resizeVertices( size )

Parameters

  • size — int, the number of vertices

Related: craft.model, model.resizeIndices

model.resizeIndices( size ) (method)

ID: model.resizeIndices
Group: Rendering

Sets the number of indices in the model where each set of 3 indices forms a triangle.

Syntax

myModel:resizeIndices( size )

Parameters

  • size — int, the number of indices

Related: craft.model, model.resizeVertices

model.position( index, ... ) (method)

ID: model.position
Group: Rendering

Set or get the position for a vertex within this model.

Use with only the index parameter to return the x, y, z values of a vertex position (as 3 separate values).

Syntax

myModel:position( index )
myModel:position( index, p )
myModel:position( index, x, y, z )

Parameters

  • index — int,

Related: craft.model, model.resizeVertices

model.normal( index, ... ) (method)

ID: model.normal
Group: Rendering

Set or get the normal for a vertex within this model.

Use with only the index parameter to return the x, y, z values of a vertex normal (as 3 separate values).

Syntax

x, y, z = myModel:normal( index )
myModel:normal( index, n )
myModel:normal( index, x, y, z )

Parameters

  • index — int,

Related: craft.model, model.resizeVertices, model.position

model.color( index, ... ) (method)

ID: model.color
Group: Rendering

Set or get the color for a vertex within this model.

Use with only the index parameter to return the r, g, b, a values of a vertex color (as 4 separate values).

Syntax

r, g, b, a = myModel:color( index )
myModel:color( index, c )
myModel:color( index, r, g, b, a )

Parameters

  • index — int,

Related: craft.model, model.resizeVertices, model.position, model.normal, model.uv

model.uv( index, ... ) (method)

ID: model.uv
Group: Rendering

Set or get the uv for a vertex within this model.

Use with only the index parameter to return the u, v values of a vertex uv (as 2 separate values).

Syntax

u, v = myModel:uv( index )
myModel:uv( index, p )
myModel:uv( index, u, v )

Parameters

  • index — int, index of the vertex to access

Related: craft.model, model.resizeVertices, model.position, model.normal, model.color

model.submeshCount (property)

ID: model.submeshCount
Group: Rendering

This returns the number of submeshes available in the model. It can be used to find the range of indices needed for the getMaterial and setMaterial methods

Note that submeshes are indexed from 1 to submeshCount

Syntax

myModel.submeshCount

Related: craft.model, craft.material, model.setMaterial, model.getMaterial

model.getMaterial( index ) (method)

ID: model.getMaterial
Group: Rendering

Get the material for a submesh within this model. You can use the submeshCount property of the model to get the number of submeshes with distinct materials

Note that submeshes are indexed from 1 to submeshCount. If an index is not provided it defaults to 1

Syntax

mat = myModel:getMaterial()
mat = myModel:getMaterial( index )

Parameters

  • index — int, index of the submesh to access, starting at 1

Related: craft.model, craft.material, model.setMaterial

model.setMaterial( material, index ) (method)

ID: model.setMaterial
Group: Rendering

Set the material for a submesh within this model. You can use the submeshCount property of the model to get the number of submeshes with distinct materials

Note that submeshes are indexed from 1 to submeshCount. If an index is not provided it defaults to 1

Syntax

myModel:setMaterial( material )
myModel:setMaterial( material, index )

Parameters

  • material — Craft material to apply to the submesh at this index
  • index — int, index of the submesh to access, starting at 1

Related: craft.model, craft.material, model.getMaterial

model.addElement( index ) (method)

ID: model.addElement
Group: Rendering

Adds a variable number of indices to the model. Each index must be within the range 1..model.vertexCount

Syntax

myModel:addElement( index1, index2, ..., indexN )

Parameters

  • index — int,

Related: craft.model, model.resizeVertices, model.position, model.normal, model.color, model.indices

model.clear (method)

ID: model.clear
Group: Rendering

Clears all buffers in all submeshes associated with this model. Effectively removing all its geometry

This is useful for re-using a model object multiple times

Syntax

myModel:clear()

Related: craft.model

model.split( index ) (method)

ID: model.split
Group: Rendering

This function modifies the model geometry to ensure that each triangle has unique vertices. So that no triangle shares vertex indexes with its neighbours. Calling this will increase the number of vertices in the model (if it is not already split)

The index parameter (defaults to 1) allows you to specify which submesh is split. If a model has multiple submeshes you will need to call split multiple times, one for each submesh up to submeshCount

Syntax

myModel:split()
myModel:split( index )

Parameters

  • index — int, index of the submesh to access, starting at 1

Related: craft.model

craft.physics (type)

ID: craft.physics
Group: Physics

The system governing all 3D physics in a scene.

Parameters

  • paused — bool, use to pause and unpause the physics simulation
  • gravity — vec3, the current force of gravity effecting all rigidbodies (measured in ms^2)

physics.raycast (function)

ID: physics.raycast
Group: Physics

Performs a raycast in the scene against any rigidbodies with attached shapes.

Syntax

scene.physics:raycast(origin, direction, distance)
scene.physics:raycast(origin, direction, distance, group)
scene.physics:raycast(origin, direction, distance, group, mask)

Parameters

  • origin — vec3, the origin of the ray
  • direction — vec3, the direction of the ray
  • distance — float, the maximum distance the ray can travel
  • group — int, the group of the ray (used for filtering)
  • mask — int, the mask of the ray (used for filtering)

Returns

table, if the raycast intersects a rigidbody this function will return a table containing the following key-value pairs:

entity => entity hit
point => point of intersection
normal => normal at the point of intersection
fraction => fraction of total ray length from start to intersecton point
uv => the uv coordinates of the hit location (if the target has an attached model shape)
barycentric => the barycentric coordinates of triangle hit location (if the target has an attached model shape)
triangleIndex => the index of the triangle hit (if the target has an attached model shape)

physics.spherecast (function)

ID: physics.spherecast
Group: Physics

Performs a spherecast in the scene against any rigidbodies with attached shapes. A spherecast works by projecting a sphere in the direction of the cast and detecting any shapes that it intersects.

Syntax

scene.physics:spherecast(origin, direction, distance, radius)
scene.physics:spherecast(origin, direction, distance, radius, group)
scene.physics:spherecast(origin, direction, distance, radius, group, mask)

Parameters

  • origin — vec3, the origin of the spherecast
  • direction — vec3, the direction of the spherecast
  • distance — float, the maximum distance the spherecast can travel
  • radius — float, the radius of the spherecast
  • group — bitmask, the group of the ray (used for filtering)
  • mask — bitmask, the mask of the ray (used for filtering)

Returns

table, if the spherecast intersects a rigidbody this function will return a table containing the following key-value pairs:

entity => entity hit
point => point of intersection
normal => normal at the point of intersection
fraction => fraction of total ray length from start to intersecton point

craft.rigidbody (type)

ID: craft.rigidbody
Group: Physics

This type represents a 3D rigidbody. Attach this to an entity to make it respond to forces and collisions. When creating a rigidbody you must specify the type you want to create. Refer to the documentation for DYNAMIC, STATIC and KINEMATIC for more details.

Syntax

myRigidbody = myEntity:add( craft.rigidbody, STATIC )
myRigidbody = myEntity:add( craft.rigidbody, KINEMATIC )
myRigidbody = myEntity:add( craft.rigidbody, DYNAMIC, mass )

Parameters

  • type — the type of the body, can be STATIC, DYNAMIC or KINEMATIC
  • mass — float, the mass of the rigid body in kilograms
  • centerOfMass — vec3, the center of mass of the rigid body in world space
  • linearVelocity — vec3, the current linear velocity of the body in meters per second
  • angularVelocity — vec3, the angular velocity of the body in degrees per second
  • awake — bool, is the rigid body currently awake
  • sleepingAllowed — bool, is sleeping allowed for this rigid body
  • linearDamping — float, linear damping factor, slows rigid body movement over time
  • angularDamping — float, angular damping factor, slows rigid body rotation over time
  • friction — float, sliding friction factor
  • rollingFriction — float, rolling friction factor
  • restitution — float, restitution factor, the bounceyness of this rigid body
  • group — bitmask, the collision filtering group for this rigid body
  • mask — bitmask, the collision filtering mask for this rigid body

Examples

-- create a sphere with a 1 meter radius
sphere = scene:entity()

-- Attach a dynamic rigidbody
sphere:add(craft.rigidbody, DYNAMIC, 1)

-- Add a sphere shape to respond to collisions
sphere:add(craft.shape.sphere, 1)

-- Attach a renderer and sphere model for visuals
sphere.model = craft.model.icosphere(1, 3)
sphere.material = craft.material(asset.builtin.Materials.Standard)

Related: DYNAMIC, STATIC, KINEMATIC

DYNAMIC (const)

ID: DYNAMIC
Group: Physics

This constant specifies the dynamic body type. Dynamic bodies move under the influence of collisions, forces, joints and gravity.

Syntax

DYNAMIC

Returns

int

Related: craft.rigidbody

STATIC (const)

ID: STATIC
Group: Physics

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: craft.rigidbody

KINEMATIC (const)

ID: KINEMATIC
Group: Physics

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: craft.rigidbody

rigidbody.applyForce( force ) (method)

ID: rigidbody.applyForce
Group: Physics

Applies a force to this rigidbody. If worldPoint is not specified then the force will be applied to the center of the rigidbody.

Syntax

myBody:applyForce( force )
myBody:applyForce( force, worldPoint )

Parameters

  • force — vec3, the amount of force (in newtons per second) to apply as a vector
  • worldPoint — vec3, the point to apply the force from, in world coordinates

Related: craft.rigidbody, rigidbody.applyTorque

rigidbody.applyTorque( torque ) (method)

ID: rigidbody.applyTorque
Group: Physics

Applies torque to this rigidbody.

Syntax

myBody:applyTorque( torque )

Parameters

  • force — vec3, the amount of torque (in newton meters per second) to apply as a vector

Related: craft.rigidbody, rigidbody.applyForce

craft.shape.box (type)

ID: craft.shape.box
Group: Physics

This component represents a box physics shape. Attach this to an entity with a rigidbody to make it respond to physical forces.

Syntax

myShape = myEntity:add(craft.shape.box, size)
myShape = myEntity:add(craft.shape.box, size, offset)

Parameters

  • size — vec3, the size of the box
  • offset — vec3, the offset of the box (center)

Examples

-- create a new entity
e = scene:entity()
e:add(craft.rigidbody, DYNAMIC, 1)
e:add(craft.shape.box, vec3(1,1,1), vec3(0,0,0))

Related: Rigidbody

craft.shape.sphere (type)

ID: craft.shape.sphere
Group: Physics

This component represents a sphere physics shape. Attach this to an entity with a rigidbody to make it respond to physical forces.

Syntax

myShape = myEntity:add(craft.shape.sphere, radius)
myShape = myEntity:add(craft.shape.sphere, radius, offset)

Examples

-- create a new entity
e = scene:entity()
e:add(craft.rigidbody, DYNAMIC, 1)
e:add(craft.shape.sphere, 1, vec3(0,0,0))

Related: craft.rigidbody

craft.shape.model (type)

ID: craft.shape.model
Group: Physics

This component represents an arbitrary physics shape made from a model. Attach this to an entity with a rigidbody to make it respond to physical forces.

Syntax

myShape = myEntity:add(craft.shape.model, model)

Examples

-- create a new entity
local model = craft.model("CastleKit:wallNarrowStairsFence")

e = scene:entity()
e.model = model
e:add(craft.rigidbody, STATIC)
e:add(craft.shape.model, model)

Related: craft.rigidbody

craft.shape.capsule (type)

ID: craft.shape.capsule
Group: Physics

This component represents a capsule physics shape. Attach this to an entity with a rigidbody to make it respond to physical forces.

Syntax

myShape = myEntity:add(craft.shape.capsule, radius, height)

Examples

-- create a new entity
e = scene:entity()
e:add(craft.rigidbody, DYNAMIC, 1)
e:add(craft.shape.capsule, 1, vec3(0,0,0))

Related: craft.rigidbody

craft.voxels (type)

ID: craft.voxels
Group: Voxels

The voxel system, used to manage streaming voxel terrain. Initially no voxels exist as the terrain is completely empty. Using voxels:resize() will create an empty patch of terrain, consisting of empty blocks. Once some terrain has been allocated voxels:generate() can be used to generate the landscape one chunk at a time via a multi-threaded generation system. See the Voxel Terrain project for an example of how this works. Using voxels:enableStorage(storage) allows voxels to be saved to a project subfolder with the specified name. As a technical note, volumes and chunks are saved as zlib compressed json files. Block types, scheduled updates and block entities are all saved. If a block id changes due to inserting a new block type of removing an existing one, the loaded chunk/volume may change unexpectedly.

Syntax

craft.voxels

Parameters

  • coordinates — vec3, the viewing coordinates to stream voxels around (in world coordinates)
  • visibleRadius — float, the radius (in chunks) to stream around the viewing coordinates
  • visibleChunks — int, the number of chunks that are loaded and potentially visible in the scene
  • generatingChunks — int, the number of chunks that are currently being generated
  • meshingChunks — int, the number of chunks that are currently being meshed (turned into models)

Examples

-- Set the size of the voxel landscape to 10x1x10 chunks
-- Each chunk is 16x128x16 blocks in size by default
scene.voxels:resize(vec3(10,1,10))
scene.voxels:generate(readProjectTab("Generate"), "generateTerrain")

Related: craft.volume

voxels.resize( sizeInChunks, chunkSize ) (method)

ID: craft.voxels.resize
Group: Voxels

Resizes the voxel terrain to a specified size divided into chunks, which can be generated and streamed efficiently.

Syntax

scene.voxels:resize( vec3(100, 1, 100) )
scene.voxels:resize( vec3(100, 1, 100), vec3(16, 128, 16) )

Parameters

  • sizeInChunks — vec3, the total size of the world in chunks (y is limited to 1 at this time)
  • chunkSize — vec3, the size of each chunk (default is 16x128x16)

Related: craft.voxels

voxels.generate( generationCode, generationFunction ) (method)

ID: craft.voxels.generate
Group: Voxels

Triggers voxel terrain generation using lua code provided as a string and the number of a function to call. The specified function must exist within generationCode and must take a single parameter which is the chunk that will be generated. See craft.volume for available methods for manipulating chunks.

Syntax

scene.voxels:generate(generationCode, generationFunction)

Parameters

  • generationCode — string, the lua code to use for multi-threaded generation
  • generationFunction — string, the name of the function within generationCode to use

Related: craft.voxels

voxels.get( coord, key ) (method)

ID: craft.voxels.get
Group: Voxels

Gets data from a block at a particular location using the specified key(s). There are a number that can be used for different block data:

BLOCK_ID - Get this block's id (int) BLOCK_NAME - Get this block's name (string) BLOCK_STATE - Get this block's state (int) COLOR - Get this block's tint color (color), only works for tinted blocks To get custom block properties, use a string with the name of that property. When called with no keys specified a block instance will be returned which has methods which can be called directly.

Syntax

scene.voxels:get ( coord, key )
scene.voxels:get ( coord, key1, key2, ... keyN )
scene.voxels:get ( coord, keyArray )

Parameters

  • coord — vec3 or (x,y,z), the coordinate of the block (in world coordinates) to get the data from
  • key — the key of the data to get for this block

Returns

multiple, the values associated with the block's keys (or nil if it does not exist)

Related: craft.scene

voxels.set( coord, key, value ) (method)

ID: craft.voxels.set
Group: Voxels

Sets data on a block at a particular location for the specified key(s). There are several that can be used for different block data:

BLOCK_ID - Set this blocks id (int), effectively changing the type of block BLOCK_NAME - Set this blocks name (string), effectively changing the type of block BLOCK_STATE - Set this blocks state (int) COLOR - Set this blocks tint color (color), only works for tinted blocks

If a block changes its own type then it will behave as the new block and will trigger any destroyed() and created() callbacks.

To modify custom block properties, use a string with the name of that property.

Syntax

scene.voxels:set ( coord, key, value )
scene.voxels:set ( coord, key1, value1, ... keyN, valueN )
scene.voxels:set ( coord, keyValueTable )

Parameters

  • coord — vec3 or (x,y,z), the coordinate of the block (in world coordinates) to set the data for
  • key — the key of the data to set for this block
  • value — the value to set the data to

Related: craft.block

voxels.fill( key, value ) (method)

ID: craft.voxels.fill
Group: Voxels

Sets the current fill block. Takes the same parameters as voxels.set. This is used for basic drawing operations such as sphere, box and line.

Syntax

scene.voxels:fill ( key )
scene.voxels:fill ( key1, key2, ... keyN )
scene.voxels:fill ( keyArray )

Parameters

  • key — the key of the data to use for the fill
  • value — the value of the data to use for the fill

Related: craft.scene

voxels.fillStyle( style ) (method)

ID: craft.voxels.fillStyle
Group: Voxels

Sets the current fill style. There are several styles that can be used:

REPLACE - Replace fill style, new blocks will replace any existing ones UNION - Union fill style, new blocks will only replace empty ones UNTERSECT - Intersect style, new blocks will only replace non-existing ones CLEAR - Clear style, new blocks will clear any existing blocks

Syntax

scene.voxels:fillStyle ( style )

Parameters

  • style — the style to use

Related: craft.scene

voxels.block( coord ) (method)

ID: craft.voxels.block
Group: Voxels

Sets a single block using the current fill() and fillStyle() settings.

Syntax

scene.voxels:block ( coord )

Parameters

  • coord — vec3 or (x,y,z), the coordinate to place the block

Related: craft.block

voxels.sphere( coord, radius ) (method)

ID: craft.voxels.sphere
Group: Voxels

Sets a sphere shaped array of blocks using the coord and radius

Syntax

scene.voxels:sphere ( coord, radius )
scene.voxels:sphere ( x, y, z, radius )

Parameters

  • coord — vec3 or (x,y,z), the coordinate of the sphere to place
  • radius — float, the radius of the sphere to place

Related: craft.block

voxels.box( min, max ) (method)

ID: craft.voxels.box
Group: Voxels

Sets a box shaped array of blocks using the minimum and maximum coordinates supplied.

Syntax

scene.voxels:box ( min, max )
scene.voxels:box ( x1, y1, z1, x2, y2, z2 )

Parameters

  • min — vec3 or (x,y,z), the coordinate of the minimum corner of the box
  • max — vec3 or (x,y,z), the coordinate of the maximum corner of the box

Related: craft.block

voxels.line( start, end ) (method)

ID: craft.voxels.line
Group: Voxels

Sets a line shaped array of blocks using the minimum and maximum coordinates supplied.

Syntax

scene.voxels:line ( start, end )
scene.voxels:line ( x1, y1, z1, x2, y2, z2 )

Parameters

  • start — vec3 or (x,y,z), the coordinate of the start of the line
  • end — vec3 or (x,y,z), the coordinate of the end of the line

Related: craft.block

voxels.updateBlock( coord, ticks ) (method)

ID: craft.voxels.updateBlock
Group: Voxels

Schedules a block update for the block at a specified coordinate. The ticks parameter controls how long in the future before the update will occur. Each tick is roughly 1/60th of a second. Using 0 will cause an update to occur next frame.

Block updates call the blockUpdate(ticks) method on scripted blocks. Block updates can be triggered inside a scripted block itself by using self:schedule(ticks).

Syntax

scene.voxels:updateBlock ( coord, ticks )
scene.voxels:updateBlock ( x, y, z, ticks )

Parameters

  • coord — vec3 or (x,y,z), the coordinate of the block to update
  • ticks — ticks, the number of ticks to wait for the update

Related: craft.block

voxels.raycast( origin, direction, distance, callback ) (method)

ID: voxels.raycast
Group: Voxels

Performs a raycast on the voxel terrain. The callback provided must follow the signature:

function callback(coord, id, face)

The coord parameter (vec3) contains the coordinate of the current voxel encountered.

If coord is nil, this means the raycast has gone outside of the bounds of the voxel terrain (i.e. no voxel found).

The id parameter contains the id of the current voxel encountered.

The face parameter (vec3) contains the direction of the face hit by the raycast (i.e. vec3(0,1,0) would be the top).

At each step the callback function can return true or false. Returning true will terminate the raycast early, false will continue the raycast until the maximum distance is reached.

Syntax

scene.voxels:raycast( start, direction, distance, callback )

Parameters

  • origin — vec3, the origin of the ray
  • direction — vec3, the direction of the ray
  • distance — vec3, the maximum distance the ray can travel
  • callback — function, a callback that will be called for each voxel encountered

Examples

-- Use the main camera to get the position and direction for the raycast from a screen location
origin, dir = craft.camera.main:screenToRay(vec2(WIDTH/2, HEIGHT/2))

scene.voxels:raycast(origin, dir, 100, function(coord, id, face)
  if coord and id ~= 0 then
    print('found a block at '..coord..' with id '..id)
    return true
  end
  return false
end)

Related: craft.voxels

voxels.iterateBounds( min, max, callback ) (method)

ID: craft.voxels.iterateBounds
Group: Voxels

Iterates through all blocks within the min and max bounds provided sending the information to a callback function. The callback function should take the following form function myCallback(x, y, z, id).

Syntax

scene.voxels:iterateBounds( min, max, callback )

Parameters

  • min — vec3 or (x,y,z), the coordinate of the minimum corner of the box
  • max — vec3 or (x,y,z), the coordinate of the maximum corner of the box
  • callback — function, the function to callback for each block encountered

Related: craft.block

voxels.isRegionLoaded( min, max ) (method)

ID: craft.voxels.isRegionLoaded
Group: Voxels

Checks if all the voxels within the min and max bounds are currently loaded. This is useful for generating more complex structures that make require adjacent areas to be loaded.

Syntax

scene.voxels:isRegionLoaded( min, max )

Parameters

  • min — vec3 or (x,y,z), the coordinate of the minimum corner of the box
  • max — vec3 or (x,y,z), the coordinate of the maximum corner of the box

Related: craft.block

voxels.enableStorage( storageName ) (method)

ID: craft.voxels.enableStorage
Group: Voxels

Enables storage within the voxel system. This causes regions to be saved within the project inside a folder named storageName.

Syntax

scene.voxels:enableStorage( storageName )

Parameters

  • storageName — string, the name of the storage folder to use

Related: craft.block

voxels.disableStorage() (method)

ID: craft.voxels.disableStorage
Group: Voxels

Disables storage.

Syntax

scene.voxels:disableStorage()

Related: craft.block

voxels.deleteStorage( storageName ) (method)

ID: craft.voxels.deleteStorage
Group: Voxels

Deletes a particular storage folder (if it exists).

Syntax

scene.voxels:deleteStorage( storageName )

Parameters

  • storageName — string, the name of the storage folder to delete

Related: craft.block

craft.block (type)

ID: craft.block
Group: Voxels

This type represents a specific voxel block variant. You can create a block type via scene.voxels.blocks:new( name ).

By default a block type has the appearance of a white cube (1x1x1 units). A block type's appearance can be customised by adding and removing cubes of various sizes, changing their textures or applying tints.

A block type's behaviour can be customised by enabling scriping and adding special methods to it:

blockType:created() - called when the block is created blockType:destroyed() - called when the block is destroyed (removed) blockType:buildModel(model) - called when the block is about to be modeled

Instances of scripted blocks cannot store additional data in their tables unless they are set to dynamic. Non-dynamic blocks have up to 32 bits of state that can be used to store per-block data (see block.state for more information). Dynamic blocks can store additional values in their tables. Dynamic blocks come with their own entity, which can be used to render custom models, or animate them in ways static blocks cannot.

Scripted and dynamic blocks use significantly more resources than standard non-scripted blocks and care must be taken to avoid using too much memory or slowing down the voxel system. A good rule of thumb is to match the complexity of a custom block to how often it is used.

Please note that any properties marked instance only can only be accessed via block instances, i.e. those created by setting voxels and passed into callbacks.

Parameters

  • id — int, the id of this block type
  • name — string, the name of this block type
  • state — type, the state of this block
  • geometry — int, the type of geometry to generate, can be EMPTY, SOLID, TRANSPARENT or TRANSLUCENT
  • renderPass — int, the type of render pass to use, can be OPAQUE or TRANSLUCENT
  • tinted — bool, whether this block type supports tinting (changing color)
  • scripted — bool, whether this block type supports scripting
  • dynamic — bool, whether this block type is dynamic
  • x — int, the x location of this block (instance only)
  • y — int, the y location of this block (instance only)
  • z — int, the z location of this block (instance only)

Related: craft.renderer

block.get( key ) (method)

ID: block.get
Group: Voxels

Gets data from this block for the specified key. There are a number of that can be used for different block data.

BLOCK_ID - Get this block's id (int) BLOCK_NAME - Get this block's name (string) BLOCK_STATE - Get this block's state (int) COLOR - Get this block's tint color (color), only works for tinted blocks To get custom block properties, use a string with the name of that property.

Syntax

myBlock:get ( key )
myBlock:get ( key1, key2, ... keyN )
myBlock:get ( keyArray )

Parameters

  • key — the key of the data to set on this block

Related: craft.block

block.set( key, value ) (method)

ID: block.set
Group: Voxels

Sets data on this block for the specified key. There are a number of that can be used for different block data.

BLOCK_ID - Set this blocks id (int), effectively changing the type of block BLOCK_NAME - Set this blocks name (string), effectively changing the type of block BLOCK_STATE - Set this blocks state (int) COLOR - Set this blocks tint color (color), only works for tinted blocks

If a block changes its own type then it will behave as the new block and will trigger any destroyed() and created() callbacks.

To modify custom block properties, use a string with the name of that property.

Syntax

myBlock:set ( key, value )
myBlock:set ( key1, value1, ... keyN, valueN )
myBlock:set ( keyValueTable )

Parameters

  • key — the key of the data to set on this block
  • value — the value to set the data to

Examples

local Blinky = scene.voxels.blocks:new("Blinky")

function Blinky:created()
  -- Schedule an update in one second
  self:schedule(60)
end

function Blinky:blockUpdate(ticks)
  -- Create a random color
  local randomColor = color(random(128,255), random(128,255), random(128,255))

  -- set block color and then schedule another update in one second
  self:set(COLOR, randomColor)
  self:schedule(60)
end

Related: craft.block

craft.volume (type)

ID: craft.volume
Group: Voxels

This component represents a 3D voxel volume. Voxel volume components store block data as well as handling rendering and physics.

Syntax

myEntity:add(craft.volume, x, y, z)

Examples

-- create a new entity
entity = scene:entity()
entity:add(craft.volume, 10, 10, 10)

Related: craft.entity

volume.size() (method)

ID: volume.size
Group: Voxels

Returns the size of this volume in voxels as 3 components (x, y, z).

Syntax

sx, sy, sz = myVolume:size()

Returns

size of the volume as 3 separate values

Examples

entity = scene:entity()
volume = entity:add(craft.volume, 10, 10, 10)
-- outputs: 10 10 10
print(volume:size())

Related: craft.volume

volume.get( coord, key ) (method)

ID: volume.get
Group: Voxels

Gets data from a block at a particular location using the specified key(s). There are a number that can be used for different block data:

BLOCK_ID - Get this block's id (int) BLOCK_NAME - Get this block's name (string) BLOCK_STATE - Get this block's state (int) COLOR - Get this block's tint color (color), only works for tinted blocks To get custom block properties, use a string with the name of that property.

Syntax

myVolume:get ( key )
myVolume:get ( key1, key2, ... keyN )
myVolume:get ( keyArray )

Parameters

  • coord — vec3 or (x,y,z), the coordinate of the block (in world coordinates) to get the data from
  • key — the key of the data to get for this block

Returns

multiple, the values associated with the block's keys (or nil if it does not exist)

Related: craft.scene

volume.set( x, y, z, id ) (method)

ID: volume.set
Group: Voxels

Sets a block within this volume at the coordinates given (x, y, z). Coordinates can be supplied as either a vec3, or as a set of 3 numbers.

Syntax

myVolume:set( x, y, z, id )
myVolume:set( coord, id )
myVolume:set( x, y, z, name )
myVolume:set( coord, name )
myVolume:set( x, y, z, key1, value1, ... keyN, valueN )
myVolume:set( coord, keyValueTable )
myVolume:set( x, y, z, keyValueTable )

Parameters

  • x — number, the x location of the block to set
  • y — number, the y location of the block to set
  • z — number, the z location of the block to set

Examples

entity = scene:entity()
volume = entity:add(craft.volume, 10, 10, 10)
-- Create a purple block inside the volume
volume:set(1, 1, 1, 'name', 'solid', 'color', color(255,0,0))

Related: craft.set

volume.resize( x, y, z ) (method)

ID: volume.resize
Group: Voxels

Resizes the volume to a specific size.

Syntax

myVolume:resize( x, y, z )

Parameters

  • x — float, the width of the volume
  • y — float, the height of the volume
  • z — float, the depth of the volume

Related: craft.volume

volume.load( asset ) (method)

ID: volume.load
Group: Voxels

Loads a saved volume.

Syntax

myVolume:load( asset.documents.MyVoxelModel )

Parameters

  • asset — asset key, the name of the asset to load

Related: craft.volume

volume.save( asset ) (method)

ID: volume.save
Group: Voxels

Saves a volume as a voxel asset.

Syntax

myVolume:save( asset.documents.MyVoxelModel )

Parameters

  • asset — asset key, the name of the asset to save

Related: craft.volume

craft.ar (type)

ID: craft.ar
Group: AR

The Augmented Reality (AR) system. Please note that to use the AR feature your device must possess an A9 or greater processor. To determine if your device supports AR, use craft.ar.isSupported.

Only some devices support AR face tracking - these include devices with a TrueDepth camera, such as the iPhone X product line (X, XR, XS, XS Max) and iPad Pro 2018 and above models. To determine if your device supports AR face tracking, use craft.ar.isFaceTrackingSupported.

To enable AR, use scene.ar:run(). This will use the sky to render the camera feed to the background. If you do not want to display the camera feed, simply disable the sky. To disable AR you can call the pause() function.

To enable AR face tracking supply an addition parameter in the form of scene.ar:run(AR_FACE_TRACKING).

In world tracking configuration the AR system will automatically try to detect and estimate horizontal and vertical planes in the scene. To be notified of when this happens you must set the anchor callbacks, such as scene.ar.didAddAnchors. These will be called with an array of anchor objects which contain a position and extent which can be used for positioning objects in the world.

To interact with the AR world, use hitTest(screenPoint, options), and check the array of hitTestResult objects for any intersections.

Parameters

  • isSupported — bool [static, readonly], use to determine if your device supports AR
  • isFaceTrackingSupported — bool [static, readonly], use to determine if your device supports AR face tracking
  • isRunning — bool [readonly], use to determine if AR is currenly active
  • planeDetection — bool, enable and disable plane detection
  • trackingState — enum [readonly], the current tracking state - can be AR_NOT_AVAILABLE, AR_LIMITED and AR_NORMAL
  • trackingStateReason — enum [readonly], the reason for the current tracking state (if AR_LIMITED) - can be AR_NONE, AR_EXCESSIVE_MOTION and AR_INSUFFICIENT_FEATURES
  • didAddAnchors — function, the function to call when one or more anchors is added to the AR system
  • didUpdateAnchors — function, the function to call when one or more anchors is updated
  • didRemoveAnchors — function, the function to call when one or more anchors is removed

ar.run() (method)

ID: ar.run
Group: AR

Enables AR if possible. This overrides the sky's visuals as well as the main camera's transform and projection matrix.

Syntax

scene.ar:run()
scene.ar:run(AR_WORLD_TRACKING)
scene.ar:run(AR_FACE_TRACKING)

Parameters

  • trackingType — constant, the type of tracking to use (i.e. AR_WORLD_TRACKING or AR_FACE_TRACKING)

Related: craft.ar, AR_WORLD_TRACKING, AR_FACE_TRACKING

ar.pause() (method)

ID: ar.pause
Group: AR

Pauses AR.

Syntax

scene.ar:pause()

Related: craft.ar

ar.hitTest( screenPoint, options ) (method)

ID: ar.hitTest
Group: AR

Performs a hit test (raycast) against the AR world. Any objects that are hit by the ray are returned as a list of craft.ar.hitTestResult.

The options parameter is a bitmask with the following flags: AR_FEATURE_POINT - Search for feature points AR_ESTIMATED_PLANE - Search for estimated horizontal surfaces AR_EXISTING_PLANE - Search for detected planes AR_EXISTING_PLANE_CLIPPED - Search for detected planes (clipped to edges)

Syntax

scene.ar:hitTest( screenPoint )

Parameters

  • screenPoint — vec2, the screen point to check for hits in the AR world
  • options — bitmask, the options to use for finding things in the AR world

Returns

array, the hitTestResult objects (if any) resulting from this hit test

Related: craft.ar, craft.ar.hitTestResult, AR_FEATURE_POINT, AR_ESTIMATED_PLANE, AR_EXISTING_PLANE, AR_EXISTING_PLANE_CLIPPED

ar.makeFaceModel() (method)

ID: ar.makeFaceModel
Group: AR

Generates an AR face model from the supplied blend shape table. This table is in the same format as the one supplied by the face anchor blendShapes property.

Syntax

scene.ar:makeFaceModel(blendShapes)

Parameters

  • blendShapes — table, the table of blend shapes to use to construct the model

Related: craft.ar, craft.ar.anchor, AR_FACE_TRACKING

craft.ar.anchor (type)

ID: craft.ar.anchor
Group: AR

An anchor in the AR world. These can represent a point (single location) or a plane (flat surface). The identifier property is useful for uniquely identifying anchors that are automatically created by plane detection.

When running an AR face tracking session, the anchor will contain additional data, such as blendShapes and faceModel.

The blendShapes property returns a table of facial expression data, where each key is a string relating to the expression and the corresponding value is a number between 0 and 1. There are a very large number of keys and so you may find it useful to use the AR Face example project to browse though them.

Parameters

  • type — int, the type of anchor
  • identifier — string, the unique identifier for this anchor
  • position — vec3, the position of this anchor (in the AR world)
  • extent — vec3, the extent of this anchor (for planes)
  • faceModel — model, a 3D model representing the detected face (for faces)
  • blendShapes — table, a table of blend shapes representing various facial expressions (for faces)
  • leftEyePosition — vec3, the position (in local face coordinates) of the left eye (for faces)
  • leftEyeRotation — quat, the rotation (in local face coordinates) of the left eye (for faces)
  • rightEyePosition — vec3, the position (in local face coordinates) of the right eye (for faces)
  • rightEyeRotation — quat, the rotation (in local face coordinates) of the right eye (for faces)
  • lookAtPoint — vec3, the estimated location that the eyes are currently looking at in local face coordinates (for faces)

craft.ar.hitTestResult (type)

ID: craft.ar.hitTestResult
Group: AR

A hit test result that is returned by the ar:hitTest() function. The type of hittest can be

Parameters

  • type — int, the type of hit test
  • identifier — string, the unique identifier for this anchor
  • position — vec3, the position of this anchor (in the AR world)
  • extent — vec3, the extent of this anchor (for planes)

Related: AR_FEATURE_POINT, AR_ESTIMATED_PLANE, AR_EXISTING_PLANE, AR_EXISTING_PLANE_CLIPPED

AR_WORLD_TRACKING (const)

ID: AR_WORLD_TRACKING
Group: AR

This constant specifies the AR world tracking session type used in the ar.run() method.

Syntax

AR_WORLD_TRACKING

Returns

int

Related: craft.ar, AR_FACE_TRACKING

AR_FACE_TRACKING (const)

ID: AR_FACE_TRACKING
Group: AR

This constant specifies the AR face tracking session type used in the ar.run() method.

Syntax

AR_FACE_TRACKING

Returns

int

Related: craft.ar, AR_WORLD_TRACKING

AR_NOT_AVAILABLE (const)

ID: AR_NOT_AVAILABLE
Group: AR

This constant specifies that AR world tracking is not currently available. Returned by ar.trackingState.

Syntax

AR_NOT_AVAILABLE

Returns

int

Related: craft.ar

AR_LIMITED (const)

ID: AR_LIMITED
Group: AR

This constant specifies that AR world tracking is currently limited. Returned by ar.trackingState, with further details returned by ar.trackingStateReason.

Syntax

AR_LIMITED

Returns

int

Related: craft.ar

AR_NORMAL (const)

ID: AR_NORMAL
Group: AR

This constant specifies that AR world tracking is currently normal. Returned by ar.trackingState.

Syntax

AR_NORMAL

Returns

int

Related: craft.ar

AR_NONE (const)

ID: AR_NONE
Group: AR

This constant specifies that AR world tracking is not currently limited. Returned by ar.trackingStateReason.

Syntax

AR_NONE

Returns

int

Related: craft.ar

AR_EXCESSIVE_MOTION (const)

ID: AR_EXCESSIVE_MOTION
Group: AR

This constant specifies that AR world tracking is currently limited due to excessive device motion. Returned by ar.trackingStateReason.

Syntax

AR_EXCESSIVE_MOTION

Returns

int

Related: craft.ar

AR_INSUFFICIENT_FEATURES (const)

ID: AR_INSUFFICIENT_FEATURES
Group: AR

This constant specifies that AR world tracking is currently limited due to insufficient feature points. This could be due to a lack of contrasting features on surfaces (such as a white table or mirrored surface). Returned by ar.trackingStateReason.

Syntax

AR_INSUFFICIENT_FEATURES

Returns

int

Related: craft.ar

AR_FEATURE_POINT (const)

ID: AR_FEATURE_POINT
Group: AR

Used by ar:hitTest as a mask for detecting feature points during hit test.

Syntax

AR_FEATURE_POINT

Returns

int

Related: craft.ar

AR_ESTIMATED_PLANE (const)

ID: AR_ESTIMATED_PLANE
Group: AR

Used by ar:hitTest as a mask for detecting estimated planes during hit test.

Syntax

AR_ESTIMATED_PLANE

Returns

int

Related: craft.ar

AR_EXISTING_PLANE (const)

ID: AR_EXISTING_PLANE
Group: AR

Used by ar:hitTest as a mask for detecting existing planes during hit test.

Syntax

AR_EXISTING_PLANE

Returns

int

Related: craft.ar

AR_EXISTING_PLANE_CLIPPED (const)

ID: AR_EXISTING_PLANE_CLIPPED
Group: AR

Used by ar:hitTest as a mask for detecting existing planes (clipped to edges) during hit test.

Syntax

AR_EXISTING_PLANE_CLIPPED

Returns

int

Related: craft.ar

Noise (overview)

ID: noiseOverview
Group: Noise

The noise library contains a series of noise modules that can be used to generate a large variety of procedural content. Use getValue(x,y,z) to generate a scalar noise value. Some modules take a number of inputs (set with setSource(input)).

Noise modules fall into the following catagories: Generators - These modules generate values directly and require no inputs Transformers - These modules transform their inputs in some way to create a new effect

Refer to each individual module's documentation to see how they work.

craft.noise.perlin (type)

ID: craft.noise.perlin
Group: Noise

A perlin noise generator module. Zero inputs.

Syntax

n = craft.noise.perlin()

Parameters

  • octaves — int, the number of octaves, controlling the detail of the noise
  • frequency — float, the frequency of the first octave
  • persistence — float, the persistence controls how rough the noise produced is
  • lacunarity — float, the lucunarity controls the multiplier between successive octaves
  • seed — int, the seed

Examples

local n = craft.noise.perlin()
local value = n:getValue(x,y,z)

craft.noise.rigidMulti (type)

ID: craft.noise.rigidMulti
Group: Noise

A rigid multi-fractal noise generator module. Zero inputs.

Syntax

n = craft.noise.rigidMulti()

Parameters

  • octaves — int, the number of octaves, controlling the detail of the noise
  • frequency — float, the frequency of the first octave
  • lacunarity — float, the lucunarity controls the multiplier between successive octaves
  • seed — int, the seed

Examples

local n = craft.noise.rigidMulti()
local value = n:getValue(x,y,z)

craft.noise.billow (type)

ID: craft.noise.billow
Group: Noise

A billow noise generator module. Zero inputs.

Syntax

n = craft.noise.billow()

Parameters

  • octaves — int, the number of octaves, controlling the detail of the noise
  • frequency — float, the frequency of the first octave
  • persistence — float, the persistence controls how rough the noise produced is
  • lacunarity — float, the lucunarity controls the multiplier between successive octaves
  • seed — int, the seed

Examples

local n = craft.noise.billow()
local value = n(x,y,z)

craft.noise.turbulence (type)

ID: craft.noise.turbulence
Group: Noise

Transformer module that distorts input using turbulent noise. One input.

Syntax

n = craft.noise.turbulence()

Parameters

  • frequency — float, the frequency of the turbulence
  • roughness — float, how rough the turbulence is
  • power — float, how much distortion to apply
  • seed — int, the seed

Examples

local n1 = craft.noise.perlin()
local n2 = craft.noise.turbulence()
n2:setSource(0, n1)
local value = n(x,y,z)

craft.noise.cache (type)

ID: craft.noise.cache
Group: Noise

Caches the source module value when evaluated at the same coordinates more than once. This can improve performance when an expensive module may be evaluated more than once within a single noise tree. One input.

Syntax

n = craft.noise.cache()

craft.noise.const (type)

ID: craft.noise.const
Group: Noise

Constant noise module. Returns a constant value at any location. Zero inputs.

Syntax

n = craft.noise.const(value)

Examples

local n = craft.noise.const(10)

-- Always returns 10
local value = n(x,y,z)

craft.noise.select (type)

ID: craft.noise.select
Group: Noise

Selects one of two noise modules based on the output of the control module and the set bounds. Three inputs.

Syntax

n = craft.noise.select()

craft.noise.gradient (type)

ID: craft.noise.gradient
Group: Noise

Returns a gradient in the y-axis mapped from zero to one. Zero inputs.

Syntax

n = craft.noise.gradient()

craft.noise.min (type)

ID: craft.noise.min
Group: Noise

Returns the minimum of two noise modules. Two inputs.

Syntax

n = craft.noise.min()

craft.noise.max (type)

ID: craft.noise.max
Group: Noise

Returns the maximum of two noise modules. Two inputs.

Syntax

n = craft.noise.max()

craft.noise.add (type)

ID: craft.noise.add
Group: Noise

Returns the addition of two noise modules. Two inputs.

Syntax

n = craft.noise.add()

craft.noise.multiply (type)

ID: craft.noise.multiply
Group: Noise

Returns the multiplication of two noise modules. Two inputs.

Syntax

n = craft.noise.multiply()

craft.noise.invert (type)

ID: craft.noise.invert
Group: Noise

Returns the negative of the source noise module. One inputs.

Syntax

n = craft.noise.invert()

craft.noise.abs (type)

ID: craft.noise.abs
Group: Noise

Returns the absolute version of the source noise module. One input.

Syntax

n = craft.noise.abs()

craft.noise.merge (type)

ID: craft.noise.merge
Group: Noise

Returns the first non-zero value of two noise modules. Two inputs.

Syntax

n = craft.noise.merge()

craft.noise.scaleOffset (type)

ID: craft.noise.scaleOffset
Group: Noise

Scales and offsets the output of a noise module. One input.

Syntax

n = craft.noise.scaleOffset()

craft.noise.displace (type)

ID: craft.noise.displace
Group: Noise

Displaces the coordinates of a noise module using three other noise modules. Four inputs.

Syntax

n = craft.noise.displace()

craft.noise.scale (type)

ID: craft.noise.scale
Group: Noise

Scales the coordinates of the input source module. One input.

Syntax

n = craft.noise.scale()

viewer.mode (property)

ID: viewer.mode
Group: Display Modes

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 the standard mode. The standard mode includes a sidebar with your output and parameters, as well as buttons to control project execution.

Syntax

viewer.mode = STANDARD |
              FULLSCREEN |
              FULLSCREEN_NO_BUTTONS

Parameters

  • mode — Either STANDARD, FULLSCREEN or FULLSCREEN_NO_BUTTONS

Returns

The current viewer mode

Examples

function setup()
    --Set the viewer to full screen
    viewer.mode = FULLSCREEN
end
function setup()
    --Set the viewer to standard
    --i.e. visible parameters and output
    viewer.mode = STANDARD
end
function setup()
    --Set the viewer to fullscreen
    --Hide back/pause/play buttons
    viewer.mode = FULLSCREEN_NO_BUTTONS
end

Related: STANDARD, FULLSCREEN, FULLSCREEN_NO_BUTTONS

viewer.framerate (property)

ID: viewer.framerate
Group: Display Modes

Sets the preferred framerate of the viewer. You can set this to values of 0, 15, 30, 60 or 120. The value 0 is the default and will use the maximum framerate of your device. Most devices support up to 60 frames per second, with some supporting up to 120 frames per second

Note that this sets the preferred framerate, you should set this to a rate you believe your project can consistently maintain. If the framerate cannot be maintained it will drop below your preferred setting to the next lower value

Syntax

viewer.framerate = 30

Parameters

  • framerate — Either 0, 15, 30, 60 or 120

Returns

The preferred framerate

Examples

function setup()
    --Set the viewer to a low framerate
    viewer.preferredFPS = 15
end

viewer.pointerLocked (property)

ID: viewer.pointerLocked
Group: Display Modes

Setting this property to true indicates the renderer's preference to lock the pointer, although the system may not honor the request. For the system to consider locking the pointer you must be running the viewer in full screen mode on your device (that is, not in split screen, or slide over on iPad, for example)

Syntax

viewer.pointerLocked = true

Parameters

  • pointerLockedtrue or false

Returns

Whether pointer locking is desired

Examples

function setup()
    -- Lock the pointer
    viewer.pointerLocked = true
end

viewer.isPresenting (property)

ID: viewer.isPresenting
Group: Display Modes

Returns a boolean indicating whether the viewer is presenting an alert or share sheet, or there is some other view obscuring the viewer

Syntax

viewer.isPresenting

Parameters

  • isPresenting — true if the viewer is presenting a view

Returns

Whether the viewer is presenting a view

Examples

function draw()
    if viewer.isPresenting == false then
        -- Do something
    end
end

viewer.runtime (property)

ID: viewer.runtime
Group: Display Modes

Returns the runtime type between LEGACY and MODERN.

Syntax

viewer.runtime

Parameters

  • runtime — LEGACY if using the legacy runtime type MODERN if using the modern runtime type

Returns

Whether the runtime type is LEGACY or MODERN

Examples

function draw()
    if viewer.runtime == MODERN then
        style.strokeWidth(5)
    else
        strokeWidth(5)
    end
end

viewer.showWarnings (property)

ID: viewer.showWarnings
Group: Display Modes

Determines whether warnings should be displayed in the viewer. For example, warnings will be printed if using deprecated Codea API. Defaults to true.

Syntax

viewer.showWarnings = false

Returns

Whether warnings should be displayed

FULLSCREEN (const)

ID: FULLSCREEN
Group: Display Modes

Use this value for viewer.mode to set the viewer to full screen mode. An exit full screen button will be visible in the lower left.

Syntax

FULLSCREEN

Related: viewer.mode

STANDARD (const)

ID: STANDARD
Group: Display Modes

When set on viewer.mode 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.

Syntax

viewer.mode = STANDARD

Related: viewer.mode

FULLSCREEN_NO_BUTTONS (const)

ID: FULLSCREEN_NO_BUTTONS
Group: Display Modes

Set this value on viewer.mode 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 viewer.close() function.

Syntax

viewer.mode = FULLSCREEN_NO_BUTTONS

Related: viewer.mode, viewer.close

Layout Overview (overview)

ID: layoutOverview
Group: Layout

Codea will run your projects in any configuration your device supports, this could be in portrait or landscape orientation, in a split-view environment, or with the sidebar taking up space in your view.

Some devices include "safe areas," these areas are regions of the screen in which you should avoid rendering your content. You can access the safe area insets through the layout.safeArea property. These values are insets, and represent how much you should inset your content from the respective edge of the view in order to ensure it remains visible and interactive.

When the view size changes, Codea calls the global function sizeChanged( width, height ) and passes it the new view size.

Examples

function setup()
end

function sizeChanged( newWidth, newHeight )
    -- This function gets called when
    -- the view size changes
end

Related: layout.horizontal, layout.vertical, layout.safeArea, CurrentOrientation

layout.safeArea (const)

ID: layout.safeArea
Group: Layout

This property contains a table specifying the current safe area insets of the viewer, access them by using layout.safeArea.top, layout.safeArea.bottom, layout.safeArea.left, and layout.safeArea.right

The safe area insets indicate how far from the respective edge of the screen you should avoid rendering your content into. For example, a safe area inset of 60 on the top edge might indicate your code is running on a device with a notched display, and so you should offset your interactive content 60 points from the top of the view in order to ensure its visibility.

Parameters

  • top — number, the safe area inset for the top of the viewer
  • left — number, the safe area inset for the left of the viewer
  • bottom — number, the safe area inset for the bottom of the viewer
  • right — number, the safe area inset for the right of the viewer

Examples

function setup()
    -- We might have a bottom safe area
    --  inset if we are running on a
    --  device with an on-screen home
    --  indicator

    print(layout.safeArea.bottom)
end

Related: layoutOverview

layout.horizontal (const)

ID: layout.horizontal
Group: Layout

This property specifies whether the viewer is running in a regular or compact horizontal layout mode. For example, when running Codea in split-view the horizontal layout mode of the viewer may switch to compact. You can use this property to switch your application into a state which may better deal with a smaller screen area.

The value of this property can be layout.COMPACT, layout.REGULAR, or layout.UNSPECIFIED

Examples

-- This example prints the size class whenever
--  the viewer size changes, try adjusting into
--  split-view and back to see the mode change

function sizeChanged(w, h)
    printSizeClass()
end

function printSizeClass()
    if layout.horizontal == layout.REGULAR then
        print("Regular size")
    else
        print("Compact size")
    end
end

Related: layoutOverview, layout.vertical

layout.vertical (const)

ID: layout.vertical
Group: Layout

This property specifies whether the viewer is running in a regular or compact vertical layout mode. The vertical layout class may change when switching from portrait to landscape orientation on certain devices. Use this property to react accordingly.

The value of this property can be layout.COMPACT, layout.REGULAR, or layout.UNSPECIFIED

Related: layoutOverview, layout.horizontal

layout.COMPACT (const)

ID: layout.COMPACT
Group: Layout

This value indicates a compact layout environment for the specified dimension

Related: layoutOverview, layout.horizontal, layout.vertical

layout.REGULAR (const)

ID: layout.REGULAR
Group: Layout

This value indicates a regular layout environment for the specified dimension

Related: layoutOverview, layout.horizontal, layout.vertical

CurrentOrientation (const)

ID: CurrentOrientation
Group: Layout

This global contains the current orientation and can be one of the following: PORTRAIT, PORTRAIT_UPSIDE_DOWN, LANDSCAPE_LEFT, LANDSCAPE_RIGHT.

Related: PORTRAIT, PORTRAIT_UPSIDE_DOWN, LANDSCAPE_LEFT, LANDSCAPE_RIGHT

PORTRAIT (const)

ID: PORTRAIT
Group: Layout

Check for this value in CurrentOrientation to detect if the device is in standard portrait orientation (home button at the bottom).

Syntax

CurrentOrientation == PORTRAIT

Related: CurrentOrientation, PORTRAIT_UPSIDE_DOWN

PORTRAIT_UPSIDE_DOWN (const)

ID: PORTRAIT_UPSIDE_DOWN
Group: Layout

Check for this value in CurrentOrientation to detect if the device is in inverted portrait orientation (home button at the top).

Syntax

CurrentOrientation == PORTRAIT_UPSIDE_DOWN

Related: CurrentOrientation, PORTRAIT

LANDSCAPE_LEFT (const)

ID: LANDSCAPE_LEFT
Group: Layout

Check for this value in CurrentOrientation to detect if the device is in landscape left orientation (home button on left).

Syntax

CurrentOrientation == LANDSCAPE_LEFT

Related: CurrentOrientation, LANDSCAPE_RIGHT

LANDSCAPE_RIGHT (const)

ID: LANDSCAPE_RIGHT
Group: Layout

Check for this value in CurrentOrientation to detect if the device is in landscape right orientation (home button on right).

Syntax

CurrentOrientation == LANDSCAPE_RIGHT

Related: CurrentOrientation, LANDSCAPE_LEFT

Using the Keyboard (overview)

ID: keyboardOverview
Group: Showing and Hiding the Keyboard

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: showKeyboard, hideKeyboard, isKeyboardShowing, keyboardBuffer

showKeyboard() (function)

ID: showKeyboard
Group: Showing and Hiding the Keyboard

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

Examples

function touched(touch)
    --Show keyboard when the screen is touched
    showKeyboard()
end

Related: hideKeyboard, isKeyboardShowing, keyboardBuffer

hideKeyboard() (function)

ID: hideKeyboard
Group: Showing and Hiding the Keyboard

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

Syntax

hideKeyboard()

Related: showKeyboard, isKeyboardShowing, keyboardBuffer

isKeyboardShowing() (function)

ID: isKeyboardShowing
Group: Showing and Hiding the Keyboard

This function returns whether the keyboard is currently active in the viewer.

Syntax

isKeyboardShowing()

Returns

true if the keyboard is showing, false if not

Related: showKeyboard, hideKeyboard, keyboardBuffer

keyboardBuffer() (function)

ID: keyboardBuffer
Group: Showing and Hiding the Keyboard

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

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

Related: showKeyboard, hideKeyboard

BACKSPACE (const)

ID: BACKSPACE
Group: Showing and Hiding the Keyboard

You can use this to check whether the key delivered to the global keyboard( key ) function was the backspace key..

Syntax

BACKSPACE

Examples

function keyboard(key)
    -- Did the user press backspace?
    if key == BACKSPACE then
        -- Do something
    end
end

Related: keyboardOverview, showKeyboard

startRecording() (function)

ID: startRecording
Group: Recording Video of Your Project

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: stopRecording, isRecording

stopRecording() (function)

ID: stopRecording
Group: Recording Video of Your Project

Use this function to stop Codea's video recording feature and save the recorded video to the device's camera roll.

Syntax

stopRecording()

Related: startRecording, isRecording

isRecording() (function)

ID: isRecording
Group: Recording Video of Your Project

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

Syntax

isRecording()

Returns

Boolean, whether Codea is recording the screen

Related: startRecording, stopRecording

viewer.close() (function)

ID: viewer.close
Group: Viewer Actions

Closes the viewer and returns to the editor. Calling viewer.close() is functionally the same as pressing the on-screen Back button. This function is useful if you are using viewer.mode with the FULLSCREEN_NO_BUTTONS mode

Syntax

viewer.close()

Examples

function touched(touch)
    --Exit if user taps
    if touch.tapCount == 1 and touch.state == ENDED then
        viewer.close()
    end
end

Related: viewer.mode, FULLSCREEN_NO_BUTTONS

viewer.restart() (function)

ID: viewer.restart
Group: Viewer Actions

Restarts the viewer, starting your project again. Calling viewer.restart() is functionally the same as pressing the on-screen Restart button. You can use this function to restart your game, for example.

Syntax

viewer.restart()

Examples

function touched(touch)
    --Restart if user taps
    if touch.tapCount == 1 and touch.state == ENDED then
        viewer.restart()
    end
end

Related: viewer.close

viewer.snapshot() (function)

ID: viewer.snapshot
Group: Viewer Actions

Captures the contents of the screen and returns it as an image

Note this only includes the rendered portion of your scene and does not include the sidebar UI

Syntax

local img = viewer.snapshot()

Returns

image, the contents of the screen

Examples

function touched(touch)
    -- Capture the screen on tap
    if touch.tapCount == 1 and touch.state == ENDED then
        snapshot = viewer.snapshot()
    end
end

Related: image

viewer.alert() (function)

ID: viewer.alert
Group: Viewer Actions

Brings up a system alert view. The message parameter specifies the message to display. The optional title parameter provides the title of the alert view. If no title is specified, the title "Alert" is used.

Syntax

viewer.alert( message )
viewer.alert( message, title )

Parameters

  • message — string, message to display
  • title — string, title of alert view

Examples

function touched(touch)
    --Show alert if user taps
    if touch.tapCount == 1 and touch.state == ENDED then
        viewer.alert( "Hello World" )
    end
end

viewer.share() (function)

ID: viewer.share
Group: Viewer Actions

Brings up a system share view for an image or text string. This allows you to share content to a third-party service, save it to your device, or copy it to the pasteboard.

Syntax

viewer.share( image )
viewer.share( string )

Parameters

  • content — image or string, content to share

Examples

function touched(touch)
    --Share the contents of the screen on tap
    if touch.tapCount == 1 and touch.state == ENDED then
        viewer.share(viewer.snapshot())
    end
end

How Codea Draws (overview)

ID: codeaOverview
Group: Overview

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: draw, setup

Using Assets (overview)

ID: assetsOverview
Group: Overview

While Codea lets you draw lines and shapes, it's far more interesting to use resources like images, sounds, and 3D models. That's where assets come in. When you call a function like sprite you need to give it an image to draw. There are a few ways to do this, the easiest is to type the code sprite() and then tap on the highlighted parentheses (). This will present the asset picker so you can visually select an image

When you do this, you'll notice that the image you select is referred to with an asset key, it might look something like asset.builtin.Planet_Cute.Icon. An asset key describes the location of a file on your device, and Codea actually checks that the file exists while you are writing your code. If you type an asset key that does not exist, you will notice that Codea puts a red marker next to your code informing you that the specified asset can't be found

Specifying Assets

Start by typing the word assets in your code followed by a dot (.), you will see the list of autocomplete suggestions appear, and these will refer to real files and folders on your device

Asset Locations

Project: to specify assets in your current project, just type asset.AssetName where "AssetName" is a file or folder in your project

Documents: to specify assets in Codea's documents folder, type asset.documents.AssetName

iCloud: to specify assets in Codea's iCloud documents folder, type asset.icloud.AssetName

Built-in: to specify assets from Codea's built-in collection of sprites, sounds and shaders, use asset.builtin.AssetName

Current: this is a special asset location that is identical to Project except when your code is running as part of a dependency. In this case, asset.current always refers to the currently running project, even if that project is a dependency included in another project. This is useful for writing reusable libraries that can be included in multiple projects

External: to specify assets added in external folder references that you have added via the asset picker, use asset.ExternalFolderName.AssetName where "ExternalFolderName" is the name of the folder you added

Creating New Assets

When you need to tell Codea where to save a file, you can use the Lua concatenation operator (..) to create an asset key to a non-existent path. For example:

saveText(asset.documents .. "readme.txt", "Hello World")

The code asset.documents .. "readme.txt" tells Codea to create a path in your documents folder pointing to file called "readme.txt"

Enumerating Assets

To get the number of files in a folder you can use the Lua length operator (#), some examples:

-- Number of files in your project
print(#assets)

-- Number of files in documents
print(#asset.documents)

-- Number of files in a folder in documents
print(#asset.documents.SomeFolder)

To list all assets in a folder you can append .all onto the folder path to return an array of the folder contents as asset keys, e.g.,

-- Get all files in the current project
-- and iterate over them, printing their
-- path

for i,v in pairs(asset.all) do
    print(i, v.path)
end

Special Cases

Codea tries to surface as many of the assets from your files into your code as it can, but sometimes you'll have files named with special characters and these won't translate into valid variable names in Lua. To access the raw contents of an asset library you can use square bracket notation, for example: asset.documents["My File (2).png"]. Codea won't be able to check whether the asset exists or offer autocomplete for this syntax

One other special case occurs if you have multiple files with identical names, but different file extensions. In this case Codea will offer them as static assets using _ext for the extension to differentiate. For example, asset.MyObject_png and asset.MyObject_obj refer to "MyObject.png" and "MyObject.obj" in your Codea project respectively

Asset Library Tracking

Finally, you can tell Codea to monitor a folder for changes by assigning a function to the updated property of the specified folder. Note that this only works on asset paths to folders, not to individual files. For example:

-- Track files in a folder in
-- documents for changes

asset.documents.MyFolder.updated = function (lib)
    print("Number of files " .. #lib)
end

-- Track files in your project

asset.updated = function (lib)
    print("Project files modified", lib)
end

Related: assets, assets.key, sprite, saveText

function draw() (event)

ID: draw
Group: Overview

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 blueish
    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: setup

function setup() (event)

ID: setup
Group: Overview

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()
    viewer.mode = STANDARD
    parameter("YPosition", 0,
              HEIGHT, HEIGHT/2)
end

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

Related: draw

clip( x, y, width, height ) (function)

ID: clip
Group: Setting Clipping Bounds

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

  • x — integer, x coordinate of the lower-left corner of the clipping rectangle
  • y — integer, y coordinate of the lower-left corner of the clipping rectangle
  • width — integer, width of the clipping rectangle
  • height — integer, height of the clipping rectangle

setContext( image ) (function)

ID: setContext
Group: Drawing Into Images

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.

An optional final argument useDepth can be specified to tell setContext to also allocate a depth buffer for the image. By default setContext will not. Allocating a depth buffer impacts performance, but allows rendering of 3D content into an image.

Syntax

setContext()
setContext( image )
setContext( image, useDepth )

Parameters

  • image — image, all drawing operations will occur on this image instead of on screen
  • useDepth — boolean, whether a depth buffer should be created for this image, defaults to false if not specified

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

Related: image

noise( x, y, z ) (function)

ID: noise
Group: Generators

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

  • x — float, x location of the sample
  • y — float, y location of the sample
  • z — float, z location of the sample

Returns

{'description': 'Perlin noise value from -1.0 to 1.0 at the given location.', 'type': 'number'}

background( red, green, blue ) (function)

ID: background
Group: Drawing

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

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

Examples

function draw()
    -- Dark blueish background
    background(0, 50, 70)

    -- Do some drawing
end

Related: color

ellipse( x, y, width, height ) (function)

ID: ellipse
Group: Drawing

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.

If only the width is specified, this is treated as the ellipse diameter (or radius, if ellipseMode( RADIUS ) is used).

The interpretation of an ellipse's x, y, width and height parameters can be specified using the ellipseMode() function. ellipseMode() is set to CENTER by default.

Syntax

ellipse( x, y, diameter )
ellipse( x, y, width, height )

Parameters

  • x — x-coordinate of the ellipse
  • y — y-coordinate of the ellipse
  • width — width of the ellipse
  • height — height of the ellipse

Related: ellipseMode, fill, stroke

rect( x, y, width, height ) (function)

ID: rect
Group: Drawing

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

  • x — x-coordinate of the lower-left corner
  • y — y-coordinate of the lower-left corner
  • width — width of the rectangle
  • height — height of the rectangle

Related: rectMode, fill, stroke

sprite( asset, x, y ) (function)

ID: sprite
Group: Drawing

Draws the sprite specified by asset. A sprite is a a bitmap graphic (such as a character, or a space ship). The asset specifies the location of the file to use for drawing

Alternatively, an image can be provided in instead of an asset to draw that image. CAMERA may also by provided in order to draw the current capture source video input.

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( asset, x, y )
sprite( asset, x, y, width )
sprite( asset, x, y, width, height )

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

Parameters

  • asset — asset key of the sprite to use, in the following format: asset.MyFileName or CAMERA
  • image — image to draw onto the screen
  • x — x-coordinate of the center of the sprite (this can be changed with spriteMode)
  • y — y-coordinate of the center of the sprite (this can be changed with spriteMode)
  • width — optional width of the sprite in pixels
  • height — optional height 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.

Examples

background(127, 127, 127, 255)
sprite(asset.builtin.Planet_Cute.Character_Boy,
       WIDTH / 2, HEIGHT / 2)
background(127, 127, 127, 255)
tint(255, 0, 0)
sprite(asset.builtin.Planet_Cute.Character_Boy,
       WIDTH / 2, HEIGHT / 2)
sprite(CAMERA, 0, 0)

Related: assetsOverview, spriteMode, tint, noTint, image, CAMERA

text( string, x, y ) (function)

ID: text
Group: Drawing

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

  • string — the text string that you would like to draw onto the screen
  • x — x-coordinate of the center of the text (this can be changed with textMode)
  • y — y-coordinate of the center of the text (this can be changed with textMode)

Examples

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

Related: font, fill, fontSize, textMode, textAlign, textWrapWidth, textSize

line( x1, y1, x2, y2 ) (function)

ID: line
Group: Drawing

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

  • x1 — x-coordinate of the first point
  • y1 — y-coordinate of the first point
  • x2 — x-coordinate of the second point
  • y2 — y-coordinate of the second point

Examples

function draw()
    background(128)
    stroke(255)
    line(10, 10, 80, 80)
end

Related: lineCapMode, stroke, strokeWidth, smooth, noSmooth

image (type)

ID: image
Group: Images

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.

image(CAMERA) can be used to capture the current frame from the camera into a static image. This is a fairly slow operation and should not be done every frame. If there is no camera frame available (due to the capture source not being available, or still being initialized), an image with width and height of 0 is created.

Syntax

image( width, height )
image.width
image.height
image(data)
image(source)

Parameters

  • source — CAMERA constant, to copy the frame from the current capture source
  • width — integer, the width of the image in pixels
  • height — integer, the height of the image in pixels
  • premultiplied — boolean, tells Codea to render this image as a premultiplied image. The default is false.
  • data — string, a sequence of bytes representing the encoded jpeg or png image data.

Returns

{'description': 'The newly created image of given width and height', 'type': '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)
img = image(CAMERA)

Related: image.get, image.set, image.copy, sprite, setContext, CAMERA

image.get( x, y ) (method)

ID: image.get
Group: Images

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

  • x — integer, x location of the pixel to query
  • y — integer, y location of the pixel to query

Returns

{'type': 'integer', 'description': '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.\n'}

Examples

r,g,b,a = myImage:get( 15, 15 )
r,g,b = myImage:get( 25, 25 )

Related: image, image.set

image.set( x, y, color ) (method)

ID: image.set
Group: Images

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

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

Examples

myImage:set( 15, 15, color(20,30,40,255) )
myImage:set( 15, 15, 20, 30, 40, 255)

Related: image, image.set, color

image.copy( x, y, w, h ) (method)

ID: image.copy
Group: Images

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

  • x — integer, x location of the leftmost pixels of the copy region.
  • y — integer, y location of the topmost pixels of the copy region
  • width — positive integer, width in pixels of the copy region
  • height — positive integer, height in pixels of the copy region

Returns

{'description': 'The newly created image with a copy of the given image or a subregion of it.', 'type': 'image'}

Examples

newImage = myImage:copy()
newImage = myImage:copy(20,40,100,100)

Related: image, image.set

translate( x, y ) (function)

ID: translate
Group: Transform

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

  • x — amount of horizontal translation, in pixels
  • y — amount of vertical translation, in pixels
  • z — amount of depth translation, in pixels

Related: rotate, scale, pushMatrix, popMatrix, resetMatrix

assets.key (type)

ID: assets.key
Group: Assets

This type represents a file (not folder) on your device. Codea creates an object of this type when you specify an asset using the asset.FileName syntax in your code

Syntax

asset.FileName

Parameters

  • name — string, the name of this file, including its extension
  • path — string, the full path to this file
  • ext — string, the file extension for this file
  • type — the type of this file, can be SPRITES, MODELS, SOUNDS, MUSIC, TEXT, SHADERS

Examples

-- Get the Main.lua file as an asset
local mainFile = asset.Main

print(mainFile.name)
print(mainFile.path)

-- Print a description of the asset key
print(mainFile)

Related: assets, assetsOverview

assets (type)

ID: assets
Group: Assets

This type represents a folder (not file) on your device. Codea creates an object of this type when you specify an asset using the asset.FolderName syntax in your code, folders can have nested subfolders and you can specify them by using .SubFolder to refer to them (where "SubFolder" is the name of your sub folder)

Syntax

asset.FolderName

Parameters

  • path — string, the full path to this folder
  • type — string, the type of this folder (if it represents a bundle type). Can be PROJECT or SHADERS
  • ext — string, the file extension of this folder, will be an empty string unless the folder has a specific extension
  • all — table, a table with every file and folder in this folder, the table is keyed by file name and the values are either assets.key (files) or assets (folders)
  • updated — function, assign a function to this property to be notified when this folder's contents have been modified, your function will be passed one argument which is an assets object of the folder being monitored

Examples

-- Get the Documents folder as an asset library
local docs = asset.documents

-- Number of files in documents
print(#docs)

-- Path to documents folder
print(docs.path)

-- Get a table with all the contents
local allDocs = docs.all

-- Get notified of updates to documents
asset.documents.updated = function (lib)
    print("Docs updated!")
end

-- Create an asset key pointing to a new file
local myFile = docs .. "newFile.txt"

Related: assets.key, assetsOverview

rotate( angle ) (function)

ID: rotate
Group: Transform

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

  • angle — amount of rotation in degrees
  • x — float, x value for the axis of rotation
  • y — float, y value for the axis of rotation
  • z — float, z value for the axis of rotation

Related: translate, scale, pushMatrix, popMatrix

scale( x, y ) (function)

ID: scale
Group: Transform

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

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

Related: rotate, translate, pushMatrix, popMatrix

zLevel( z ) (function)

ID: zLevel
Group: Transform

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

  • z — float, the amount of depth for future drawing operations, use positive values to draw in front, and negative values to draw behind.

Related: translate, pushMatrix, popMatrix

perspective( fov, aspect, near, far ) (function)

ID: perspective
Group: Advanced Transform

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

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

Related: projectionMatrix, ortho, camera, matrix, WIDTH, HEIGHT

ortho( left, right, bottom, top ) (function)

ID: ortho
Group: Advanced Transform

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

  • left — float, left edge of the frustum
  • right — float, right edge of the frustum
  • bottom — float, bottom edge of the frustum
  • top — float, top edge of the frustum

Related: projectionMatrix, perspective, camera, matrix, WIDTH, HEIGHT

camera(eyeX,eyeY,eyeZ, cX,cY,cZ, upX,upY,upZ) (function)

ID: camera
Group: Advanced Transform

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

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

Related: viewMatrix, perspective, matrix, WIDTH, HEIGHT

applyMatrix( matrix ) (function)

ID: applyMatrix
Group: Advanced Transform

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

  • matrix — matrix, the transformation to multiply against the current world transform

Related: modelMatrix, matrix, pushMatrix, translate

modelMatrix() (function)

ID: modelMatrix
Group: Advanced Transform

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

  • matrix — matrix, the transformation to set as the current world transform

Returns

{'description': 'The current model matrix when called with no arguments', 'type': 'matrix'}

Related: viewMatrix, projectionMatrix, matrix, pushMatrix

viewMatrix() (function)

ID: viewMatrix
Group: Advanced Transform

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

  • matrix — matrix, the transformation to set as the current view transform

Returns

{'description': 'The current view matrix when called with no arguments', 'type': 'matrix'}

Related: modelMatrix, camera, projectionMatrix, matrix

projectionMatrix() (function)

ID: projectionMatrix
Group: Advanced Transform

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

  • matrix — matrix, the transformation to set as the current projection transform

Returns

{'description': 'The current projection matrix when called with no arguments', 'type': 'matrix'}

Related: modelMatrix, perspective, ortho, viewMatrix, matrix

color (type)

ID: color
Group: Style

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

  • r — int, the red component of this color from 0 to 255
  • g — int, the green component of this color from 0 to 255
  • b — int, the blue component of this color from 0 to 255
  • a — int, the alpha component of this color from 0 to 255

Returns

{'description': 'color, a color type with the specified components', 'type': 'color'}

Examples

--Fill with red
c = color( 255, 0, 0 )
fill( c )

Related: fill, stroke, tint, background

color.blend( c ) (method)

ID: color.blend
Group: Style

This method computes a color by blending two color types. Colors are blended based on the first color's alpha value. The blend amount is determined by the alpha value of the color invoking this method.

Syntax

c1 = color( 0, 0, 0, 128 )
c2 = color( 255, 255, 255, 255 )
c3 = c1:blend( c2 )

Parameters

  • c — color, compute the blending between this color and c

Returns

{'description': 'Color computed by blending this color and c', 'type': 'color'}

Related: color, color.mix

color.mix( c, amount ) (method)

ID: color.mix
Group: Style

This method computes a color by mixing two color types linearly. Colors are blended based on the specified mix value, amount. A value of 0.5 for amount will generate a color that is half way between the two input colors.

Syntax

c1 = color( 255, 0, 0, 255 )
c2 = color( 0, 255, 0, 255 )
c3 = c1:mix( c2, 0.5 )

Parameters

  • c — color, compute the mixing between this color and c
  • amount — scalar, amount of contribution from either color. A value of 0.0 will result in the starting color, and 1.0 will result in the destination color.

Returns

{'description': 'Color computed by mixing this color and c by amount', 'type': 'color'}

Related: color, color.blend

blendMode( MODE ) (function)

ID: blendMode
Group: Style

Sets the blend mode for all further drawing. The blend mode decides how new drawing operations are blended with underlying pixels.

The default blend mode is blendMode( NORMAL ), this blends graphics according to their alpha value. NORMAL will cause drawing operations to replace the underlying pixels where the alpha value is 1.0, and mix with the underlying pixels where alpha is less than 1.0.

ADDITIVE blend mode blends drawing operations by adding color. Using this mode will cause overlapping drawing to tend towards white. This allows for glowing effects, and is useful for particle rendering (e.g. sparks, glows, fire).

MULTIPLY blend mode blends drawing operations by multiplying color. Using this mode will cause overlapping drawing to tend towards black.

More advanced blend modes can be set up by using the advanced two and four parameter versions of the function. Advanced blend modes parameters are similar to the OpenGL functions glBlendFunc and glBlendFuncSeparate.

Calling blendMode() with no arguments will return the current blend mode (multiple values will returned if an advanced blend mode is set, up to four values can be returned).

Syntax

blendMode()
blendMode( NORMAL | ADDITIVE | MULTIPLY )
blendMode( srcFactor, destFactor )
blendMode( srcFactor, destFactor,
           srcAlpha, destAlpha )

Parameters

  • mode — either NORMAL, MULTIPLY or ADDITIVE

NORMAL: specifies normal alpha-based blending

MULTIPLY: specifies multiplicative blending

ADDITIVE: specifies additive blending

  • srcFactorZERO ONE DST_COLOR ONE_MINUS_DST_COLOR SRC_ALPHA ONE_MINUS_SRC_ALPHA DST_ALPHA ONE_MINUS_DST_ALPHA SRC_ALPHA_SATURATE
  • destFactorZERO ONE SRC_COLOR ONE_MINUS_SRC_COLOR SRC_ALPHA ONE_MINUS_SRC_ALPHA DST_ALPHA ONE_MINUS_DST_ALPHA
  • srcAlpha — When this parameter is used, the factor specified for srcAlpha will be used to determine how to calculate the alpha value of the source fragment.
  • destAlpha — When this parameter is used, the factor specified for destAlpha will be used to determine how to calculate the alpha value of the destination fragment.

Returns

{'description': 'The current blend mode if called without arguments (up to four values can be returned). Returns nothing if called with arguments.'}

blendEquation( equation ) (function)

ID: blendEquation
Group: Style

Sets the blend equation for all further drawing. The blend equation determines how the destination pixels are computed given the current blend mode (see blendMode)

By default, the terms in the blend mode are added together to determine the color of the resulting pixel. Using this function you can change the operator to ADD, SUBTRACT, REVERSE_SUBTRACT, MIN, and MAX

Syntax

blendEquation()
blendEquation( ADD | SUBTRACT | REVERSE_SUBTRACT | MIN | MAX )
blendEquation( equation )
blendEquation( equation, alphaEquation )

Parameters

  • equation — Can be either ADD, SUBTRACT, REVERSE_SUBTRACT, MIN or MAX

Given source (S) and destination (D) pixels, the operators perform the following:

ADD: S + D

SUBTRACT: S - D

REVERSE_SUBTRACT: D - S

MIN: min(S, D)

MAX: max(S, D)

  • alphaEquation — An optional second parameter specifying the equation to use when blending the alpha components

Returns

{'description': 'The current blend equation and alpha equation if called without arguments. Returns nothing if called with arguments.'}

Related: blendMode

ellipseMode( MODE ) (function)

ID: ellipseMode
Group: Style

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

Syntax

ellipseMode()
ellipseMode(CENTER|RADIUS|CORNER|CORNERS)

Parameters

  • mode — either CENTER, RADIUS, CORNER or CORNERS

CENTER: x, y specifies the center of the ellipse, w, h specify its x and y diameter.

RADIUS: x, y specifies the center of the ellipse, w, h specify its x and y radius.

CORNER: x, y specifies the lower left corner of the ellipse, w, h specify the size its x and y diameter.

CORNERS: x, y sets the lower left coordinate of the ellipse's bounding box. w, h sets the upper right coordinate of the ellipse's bounding box.

Returns

{'description': 'The current ellipse mode if called without arguments. Returns nothing if called with arguments.'}

Related: ellipse

rectMode( MODE ) (function)

ID: rectMode
Group: Style

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

Syntax

rectMode()
rectMode(CENTER|RADIUS|CORNER|CORNERS)

Parameters

  • mode — either CENTER, RADIUS, CORNER or CORNERS

CENTER: x, y specifies the center of the rectangle, w, h specifies the rectangle's width and height.

RADIUS: x, y specifies the center of the rectangle, w, h specifies half the rectangle's width and height.

CORNER: x, y specifies the lower left corner of the rectangle, w and h specify the rectangle's width and height.

CORNERS: x, y sets the lower left coordinate of the rectangle's bounding box. w, h sets the upper right coordinate of the rectangle's bounding box.

Returns

{'description': 'The current rect mode if called without arguments. Returns nothing if called with arguments.'}

Related: rect

spriteMode( MODE ) (function)

ID: spriteMode
Group: Style

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

Syntax

spriteMode()
spriteMode( CENTER|RADIUS|CORNER|CORNERS )

Parameters

  • mode — either CENTER, RADIUS, CORNER or CORNERS

CENTER x, y specifies the center of the sprite, w, h specifies the sprite's width and height.

RADIUS x, y specifies the center of the sprite, w, h specifies half the sprite's width and height.

CORNER x, y specifies the lower left corner of the sprite, w and h specify the sprite's width and height.

CORNERS x, y sets the lower left coordinate of the sprite's bounding box. w, h sets the upper right coordinate of the sprite's bounding box.

Returns

{'description': 'The current sprite mode if called without arguments. Returns nothing if called with arguments.'}

Related: sprite

spriteSize( asset ) (function)

ID: spriteSize
Group: Style

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

If the sprite name represents a multi-page PDF, then this function will return three values: width, height, and page count.

Syntax

w, h = spriteSize(asset.builtin.Planet_Cute.Character_Boy)
w, h = spriteSize( image )

Parameters

  • name — asset key for the sprite, e.g., asset.MyFileName
  • image — image object

Returns

{'description': 'Width and height of the sprite specified by asset, or image object', 'type': 'integer'}

Related: assetsOverview, sprite, image

textMode( MODE ) (function)

ID: textMode
Group: Style

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

Syntax

textMode()
textMode( CENTER|CORNER )

Parameters

  • mode — either CENTER or CORNER

CENTER: x, y specifies the center of the text.

CORNER: x, y specifies the lower left corner of the text.

Returns

{'description': 'The current text mode if called without arguments. Returns nothing if called with arguments.'}

Related: text

lineCapMode( MODE ) (function)

ID: lineCapMode
Group: Style

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

  • mode — either ROUND, SQUARE or PROJECT

ROUND: line ends are rounded with circles

SQUARE: line ends are squared off at the end points

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

Returns

{'description': 'The current line cap mode if called without arguments. Returns nothing if called with arguments.'}

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)

Related: line, stroke, strokeWidth

fill( red, green, blue, alpha ) (function)

ID: fill
Group: Style

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

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

Returns

{'description': 'Four values (r,g,b,a) representing the current fill color if called without arguments. Returns nothing if called with arguments.', 'type': 'integer'}

Related: noFill, stroke, color

noFill() (function)

ID: noFill
Group: Style

Sets the color of the fill to completely transparent.

Syntax

noFill()

Related: fill, noStroke

tint( red, green, blue, alpha ) (function)

ID: tint
Group: Style

Sets the color used to tint sprites drawn with the sprite() function. This color is multiplied with the sprite'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

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

Returns

{'description': 'Four values (r,g,b,a) representing the current tint color if called without arguments. Returns nothing if called with arguments.', 'type': 'integer'}

Examples

background(127, 127, 127, 255)
tint(255, 0, 0)
sprite(asset.builtin.Planet_Cute.Character_Boy, WIDTH / 2, HEIGHT / 2)

Related: sprite, noTint

noTint() (function)

ID: noTint
Group: Style

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

Syntax

noTint()

Related: tint, sprite

stroke( red, green, blue, alpha ) (function)

ID: stroke
Group: Style

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

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

Returns

{'description': 'Four values (r,g,b,a) representing the current stroke color if called without arguments. Returns nothing if called with arguments.', 'type': 'integer'}

Related: strokeWidth, noStroke, fill

strokeWidth( width ) (function)

ID: strokeWidth
Group: Style

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

  • width — int or float, the width in pixels of the stroke

Returns

{'description': 'The current stroke width if called without arguments. Returns nothing if called with arguments.', 'type': 'number'}

Related: stroke, noStroke

noStroke() (function)

ID: noStroke
Group: Style

Sets the stroke width to zero.

Syntax

noStroke()

Related: stroke, strokeWidth

smooth() (function)

ID: smooth
Group: Style

This enables smooth line drawing, texture filtering and antialiasing. Lines will appear anti-aliased and respect styles set using the lineCapMode() function. Sprite textures will appear smoother when scaled, and primitive shapes will have antialiased edges

Syntax

smooth()

Related: noSmooth, line, lineCapMode

noSmooth() (function)

ID: noSmooth
Group: Style

This disables smooth line drawing, texture filtering and antialiasing. Lines will appear aliased, scaled sprites will have pixellated textures, and primitive shapes, such as ellipse, will no longer have antialiased edges

Use this option to draw very thin lines clearly, or to draw pixel-art style graphics.

Syntax

noSmooth()

Related: smooth, line, lineCapMode

font( name ) (function)

ID: font
Group: Style

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

  • name — string, the name of the font to use. A list of available fonts can be found by tapping on the font() function in the code editor.

Returns

{'description': 'The current font if called without arguments. Returns nothing if called with arguments.', 'type': 'string'}

Related: text, fontSize

fontSize( size ) (function)

ID: fontSize
Group: Style

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

  • size — float, the size of the font (in points). Must be greater than 0.0.

Returns

{'description': 'The current font size if called without arguments. Returns nothing if called with arguments.', 'type': 'number'}

Related: text, font

fontMetrics() (function)

ID: fontMetrics
Group: Style

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.

Syntax

fontMetrics()

Returns

{'type': 'table', 'description': 'A table containing the following keys:\n ascent\n descent\n leading\n xHeight\n capHeight\n underlinePosition\n underlineThickness\n slantAngle\n size\n'}

Related: font, fontSize

textAlign( ALIGN ) (function)

ID: textAlign
Group: Style

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

  • ALIGN — Can be LEFT, CENTER or RIGHT

Returns

{'description': 'The current text alignment if called without arguments. Returns nothing if called with arguments.'}

Related: text, textWrapWidth

textWrapWidth( width ) (function)

ID: textWrapWidth
Group: Style

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

  • width — float, width before the text rendered by text() word-wraps

Returns

{'description': 'The current text wrap width if called without arguments. Returns nothing if called with arguments.', 'type': 'number'}

Examples

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

Related: text, textAlign

textSize( string ) (function)

ID: textSize
Group: Text Metrics

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

  • string — string, the string to measure

Returns

{'description': 'width and height of the text string when rendered with the current font size and style.', 'type': 'number'}

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)

Related: text

pushMatrix() (function)

ID: pushMatrix
Group: Transform Management

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: popMatrix, resetMatrix, translate, rotate, scale

popMatrix() (function)

ID: popMatrix
Group: Transform Management

The popMatrix() 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: pushMatrix, resetMatrix, translate, rotate, scale

resetMatrix() (function)

ID: resetMatrix
Group: Transform Management

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: pushMatrix, popMatrix, translate, rotate, scale

pushStyle() (function)

ID: pushStyle
Group: Style Management

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(), font(), fontSize(), textAlign(), textMode() and textWrapWidth()

Syntax

pushStyle()

Related: popStyle, resetStyle

popStyle() (function)

ID: popStyle
Group: Style Management

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: pushStyle, resetStyle

resetStyle() (function)

ID: resetStyle
Group: Style Management

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: pushStyle, popStyle

WIDTH (const)

ID: WIDTH
Group: Constants

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

Syntax

WIDTH

Returns

{'description': 'Width of the screen in pixels', 'type': 'integer'}

Related: HEIGHT

HEIGHT (const)

ID: HEIGHT
Group: Constants

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

Syntax

HEIGHT

Returns

{'description': 'Height of the screen in pixels', 'type': 'integer'}

Related: WIDTH

ElapsedTime (const)

ID: ElapsedTime
Group: Variables

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

Syntax

ElapsedTime

Returns

{'description': 'Time in seconds since the start of running the project', 'type': 'number'}

Related: DeltaTime

DeltaTime (const)

ID: DeltaTime
Group: Variables

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

Syntax

DeltaTime

Returns

{'description': 'Time in seconds since the start of the previous frame', 'type': 'number'}

Related: ElapsedTime

ContentScaleFactor (const)

ID: ContentScaleFactor
Group: Variables

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

{'description': 'Content scale factor of the viewer', 'type': 'integer'}

cameraSource( source ) (function)

ID: cameraSource
Group: Camera Input

Calling cameraSource() will either set the current capture source, or return the currently selected one if called with no parameters.

The capture source determines which input source is used when the CAMERA constant is used in the image() and sprite() functions and as a mesh texture.

CAMERA_BACK is the default capture source.

If camera access is not authorized, or camera hardware is not available, cameraSource() will return the value -1

To get the dimensions of the current capture source frame, use spriteSize(CAMERA)

Syntax

cameraSource( source )
cameraSource()

Parameters

  • source — Either CAMERA_FRONT or CAMERA_BACK, determines the source to use.

Returns

{'description': 'CAMERA_FRONT or CAMERA_BACK if called without arguments, or -1 if camera access is unavailble. Returns nothing if called with arguments, or -1 if camera access is unavailable.\n'}

Examples

cameraSource( CAMERA_FRONT )
cameraSource( CAMERA_BACK )
currentSource = cameraSource()

Related: image, sprite, spriteSize, CAMERA, CAMERA_DEPTH, CAMERA_FRONT, CAMERA_BACK

CAMERA (const)

ID: CAMERA
Group: Camera Input

Uses the current capture source for images, sprites and textures on meshes.

CAMERA is a special constant that can be used with image(), sprite() and mesh.texture. When used with image() it provides an image containing a single snapshot from the device camera. When used with sprite() and mesh.texture it provides a live stream of the device's camera.

Syntax

CAMERA

Examples

img = image(CAMERA)
sprite(CAMERA, x, y)

local m = mesh()
m.texture = CAMERA

Related: image, sprite, mesh

CAMERA_DEPTH (const)

ID: CAMERA_DEPTH
Group: Camera Input

Uses the current capture source for images, sprites and textures on meshes.

CAMERA_DEPTH is a special constant that can be used with image(), sprite() and mesh.texture. When used with image() it provides an image containing a single snapshot from the device's estimated depth camera when used on supported devices. When used with sprite() and mesh.texture it provides a live stream of the device's depth camera.

Note that generally only the CAMERA_FRONT source will support depth sensing, and only on devices with a TrueDepth camera system.

Syntax

CAMERA_DEPTH

Examples

img = image(CAMERA_DEPTH)
sprite(CAMERA_DEPTH, x, y)

local m = mesh()
m.texture = CAMERA_DEPTH

Related: image, sprite, mesh

CAMERA_FRONT (const)

ID: CAMERA_FRONT
Group: Camera Input

Select the front camera of the device for use when using CAMERA.

Syntax

CAMERA_FRONT

Related: CAMERA, cameraSource

For Loops Overview (overview)

ID: for
Group: Overview

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: ipairs, pairs

Conditionals Overview (overview)

ID: conditionals
Group: Overview

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

While Loops Overview (overview)

ID: loops
Group: Overview

Use while and repeat loops to repeat code until a condition is true. While loops are used when you can't predict the number of times a loop will iterate, such as when reading input from a file or testing for a key press.

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

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

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

Annotations Overview (overview)

ID: annotations
Group: Overview

Annotations can be used to indicate the type of a variable to Codea, giving you better auto-completion support.

To write a code annotation, start a comment with three dashes (---). Codea will look at the next line of code to try and auto-complete your comment if it is an assignement or function definition. You can also manually write annotations anywhere in your code following the format --- variableName: variableType.

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

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

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

Related: objc

ipairs( table ) (function)

ID: ipairs
Group: Language

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

  • table — table to iterate over

Returns

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

Related: for, pairs

pairs( table ) (function)

ID: pairs
Group: Language

pairs can be used to iterate over a tables 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

  • table — table to iterate over

Returns

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

Related: for, ipairs

table.concat( table, sep ) (function)

ID: table.concat
Group: Tables

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

  • table — table to concatenate
  • sep — separator string
  • i — int, starting index to concatenate from
  • j — int, ending index

Returns

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

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

ID: table.move
Group: Tables

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

Syntax

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

Parameters

  • a1 — table to move elements from
  • f — integer, starting index in table to move from
  • e — integer, ending index in table to move from
  • t — integer, starting index in table to move into
  • a2 — table to move elements into (defaults to a1)

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

ID: table.insert
Group: Tables

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

  • table — table to insert into
  • pos — int, position to inset
  • value — value to insert

Related: table.remove

table.remove( table, pos ) (function)

ID: table.remove
Group: Tables

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

  • table — table to insert into
  • pos — int, position of value to remove

Returns

Value of the removed element

Related: table.insert

table.pack(...) (function)

ID: table.pack
Group: Tables

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

Syntax

table.pack( ... )

Parameters

  • ... — arguments to pack into table

Returns

table with all parameters packed

Related: table.unpack

table.unpack(list) (function)

ID: table.unpack
Group: Tables

Returns the elements from the given list.

Syntax

table.unpack( list )

Parameters

  • list — list to unpack

Returns

elements unpacked from list

Related: table.pack

table.sort( table ) (function)

ID: table.sort
Group: Tables

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

  • table — the table to sort
  • comp — a function that receives two table elements and returns true when the first is less than the second

os.clock() (function)

ID: os.clock
Group: Date and Time

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 ) (function)

ID: os.difftime
Group: Date and Time

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

  • t2 — Ending time
  • t1 — Starting time

Returns

Number of seconds from time t1 to time t2.

Related: os.time

os.date( format ) (function)

ID: os.date
Group: Date and Time

Returns a string or a table containing the date and time, formatted according to the given string format.

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

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

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

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

Syntax

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

Parameters

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

Returns

A string or a table containing the date and time.

Related: os.time, os.setlocale

os.setlocale( locale ) (function)

ID: os.setlocale
Group: Date and Time

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

  • locale — String specifying a locale, can be nil or the empty string.
  • category — String specifying a category to set, can be "all", "collate", "ctype", "monetary", "numeric", or "time"

Returns

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

Related: os.date, os.time

os.time() (function)

ID: os.time
Group: Date and Time

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

  • table — This table must have fields year, month, and day, and may have fields hour, min, sec, and isdst

Returns

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

Related: os.date, os.setlocale, os.difftime

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

ID: string.byte
Group: Strings

Returns the internal numerical codes of the characters s[i], s[i+1], ..., s[j]. The default value for i is 1; the default value for j is i. These indices are corrected following the same rules of string.sub.

Syntax

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

Parameters

  • s — string to use
  • i — first index, defaults to 1
  • j — last index, defaults to i

Returns

The internal numerical codes for characters s[i] up to s[j]

Related: string.char

string.char( ... ) (function)

ID: string.char
Group: Strings

Returns a string with length equal to the number of arguments, in which each character has the internal numerical code equal to its corresponding argument.

Syntax

string.char( ... )

Parameters

  • ... — a variable number of numerical codes

Returns

String composed of characters equal to the numerical codes used as arguments

Related: string.byte

string.dump( function ) (function)

ID: string.dump
Group: Strings

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

Syntax

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

Parameters

  • function — a function to convert to binary string
  • strip — boolean, whether to strip debug information

Returns

Binary string representation of the specified function

string.find( s, pattern ) (function)

ID: string.find
Group: Strings

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

  • s — string to search in
  • pattern — pattern to look for
  • init — starting character in string to search from, default is 1
  • plain — boolean, perform a plain substring search

Returns

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

Related: patterns

string.format( formatstring, ... ) (function)

ID: string.format
Group: Strings

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

  • formatstring — string defining the format

Returns

A formatted string

Examples

s = string.format("Number is %d", 5)
print( s )
-- prints "Number is 5"

string.len( s ) (function)

ID: string.len
Group: Strings

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

Syntax

string.len( s )

Parameters

  • s — get the length of this string

Returns

Length of string s

string.gmatch( s, pattern ) (function)

ID: string.gmatch
Group: Strings

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

Syntax

string.gmatch( s, pattern )

Parameters

  • s — string to search
  • pattern — pattern to match

Returns

Iterator function over matches of pattern within the string

Examples

-- Print each word in string
s = "hello world from Lua"
for w in string.gmatch(s,"%a+") do
  print(w)
end
-- Generate table from string
t = {}
s = "from=world, to=Lua"
for k, v in string.gmatch(s,"(%w+)=(%w+)") do
  t[k] = v
end

Related: patterns, string.gsub

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

ID: string.gsub
Group: Strings

Returns a copy of s in which all (or the first n, if given) occurrences of the pattern (see Patterns Overview) have been replaced by a replacement string specified by repl, which can be a string, a table, or a function. gsub also returns, as its second value, the total number of matches that occurred. The name gsub comes from Global SUBstitution.

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

If repl is a table, then the table is queried for every match, using the first capture as the key.

If repl is a function, then this function is called every time a match occurs, with all captured substrings passed as arguments, in order.

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

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

Syntax

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

Parameters

  • s — string to substitute
  • pattern — pattern to match
  • repl — string, table or function, replacement parameter
  • n — integer, number of occurrences to match (all if not specified)

Returns

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

Examples

x = string.gsub("hello world",
                "(%w+)", "%1 %1")

Related: patterns, string.gmatch

string.lower( s ) (function)

ID: string.lower
Group: Strings

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

  • s — get a lowercase version of this string

Returns

Lowercase version of string s

Related: string.upper

string.upper( s ) (function)

ID: string.upper
Group: Strings

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

  • s — get an uppercase version of this string

Returns

Uppercase version of string s

Related: string.lower

string.match( s, pattern ) (function)

ID: string.match
Group: Strings

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

  • s — string to search
  • pattern — pattern to match
  • init — starting location in string

Returns

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

Related: string.find

string.rep( s, n ) (function)

ID: string.rep
Group: Strings

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

Syntax

string.rep( s, n )

Parameters

  • s — string to replicate
  • n — int, number of times to replicate the string

Returns

n concatenations of string s

string.reverse( s ) (function)

ID: string.reverse
Group: Strings

This function returns the string s reversed.

Syntax

string.reverse( s )

Parameters

  • s — string to reverse

Returns

s reversed

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

ID: string.sub
Group: Strings

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

  • s — find substring of this string
  • i — int, starting index
  • j — int, ending index

Returns

Substring of string s

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

ID: string.pack
Group: Strings

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

Syntax

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

Parameters

  • fmt — format string specifying binary format
  • ... — arguments to pack

Returns

Values packed into binary string

Related: string.packsize, string.unpack

string.packsize( fmt ) (function)

ID: string.packsize
Group: Strings

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

Syntax

string.packsize( fmt )

Parameters

  • fmt — format string specifying binary format

Returns

Size of string packed with the given format

Related: string.pack, string.unpack

string.unpack( fmt, s ) (function)

ID: string.pack
Group: Strings

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

Syntax

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

Parameters

  • fmt — format string specifying binary format
  • s — string to unpack

Returns

The values packed in s

Related: string.pack

Patterns Overview (overview)

ID: patterns
Group: Strings

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

Character Class

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

x: (where x is not one of the magic characters
   ^$()%.[]*+-?) represents the character x
   itself.
.: (a dot) represents all characters.
%a: represents all letters.
%c: represents all control characters.
%d: represents all digits.
%g: represents all printable characters except space.
%l: represents all lowercase letters.
%p: represents all punctuation characters.
%s: represents all space characters.
%u: represents all uppercase letters.
%w: represents all alphanumeric characters.
%x: represents all hexadecimal digits.
%x: (where x is any non-alphanumeric character)
    represents the character x.
    This is the standard way to escape
    the magic characters. Any non-alphanumeric
    character (including all punctuations, even
    the non-magical) can be preceded by a '%'
    when used to represent itself in a pattern.
[set]: represents the class which is
    the union of all characters in set.
    A range of characters can be specified
    by separating the end characters of the
    range, in ascending order, with a '-'.
    All classes %x described above can
    also be used as components in set.
    All other characters in set represent
    themselves. For example, [%w_] (or [_%w])
    represents all alphanumeric characters
    plus the underscore, [0-7] represents
    the octal digits, and [0-7%l%-] represents
    the octal digits plus the lowercase letters
    plus the '-' character.
[^set]: represents the complement of set,
    where set is interpreted as above.

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

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

Pattern Item

A pattern item can be:

- a single character class, which matches
  any single character in the class;
- a single character class followed by '*',
  which matches zero or more repetitions
  of characters in the class. These
  repetition items will always match
  the longest possible sequence;
- a single character class followed by '+',
  which matches one or more repetitions of
  characters in the class. These repetition
  items will always match the longest
  possible sequence;
- a single character class followed by '-',
  which also matches zero or more repetitions
  of characters in the class. Unlike '*',
  these repetition items will always match
  the shortest possible sequence;
- a single character class followed by '?',
  which matches zero or one occurrence of
  a character in the class. It always
  matches one occurrence if possible;
- %n, for n between 1 and 9; such item
  matches a substring equal to the n-th
  captured string (see below);
- %bxy, where x and y are two distinct
  characters; such item matches strings
  that start with x, end with y,
  and where the x and y are balanced.
  This means that, if one reads the string
  from left to right, counting +1 for an x
  and -1 for a y, the ending y is the first
  y where the count reaches 0.
  For instance, the item %b() matches
  expressions with balanced parentheses.
- %f[set], a frontier pattern; such item
  matches an empty string at any position
  such that the next character belongs to
  set and the previous character does not
  belong to set. The set set is interpreted
  as previously described. The beginning
  and the end of the subject are handled
  as if they were the character '\0'.

Pattern

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

Captures

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

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

math.abs( value ) (function)

ID: math.abs
Group: Math

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

Syntax

math.abs( value )

Parameters

  • value — int or float, the number to get the absolute value of

Returns

The absolute value of value

math.acos( value ) (function)

ID: math.acos
Group: Math

This function returns the arc cosine of value in radians

Syntax

math.acos( value )

Parameters

  • value — int or float, compute the arc cosine of this number

Returns

The arc cosine of value in radians

Related: math.asin, math.atan

math.asin( value ) (function)

ID: math.asin
Group: Math

This function returns the arc sine of value in radians

Syntax

math.asin( value )

Parameters

  • value — int or float, compute the arc sine of this number

Returns

The arc sine of value in radians

Related: math.acos, math.atan

math.atan( y, x ) (function)

ID: math.atan
Group: Math

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

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

Syntax

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

Parameters

  • y — number, numerator for arc tangent
  • x — number, denominator for arc tangent (defaults to 1)

Returns

The arc tangent of y/x in radians

Related: math.asin, math.acos

math.ceil( value ) (function)

ID: math.ceil
Group: Math

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

  • value — int or float, compute the smallest integer larger than or equal to this number

Returns

The smallest integer larger than or equal to value

Related: math.floor

math.cos( value ) (function)

ID: math.cos
Group: Math

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

Syntax

math.cos( value )

Parameters

  • value — int or float, compute the cosine of this number

Returns

Cosine of value

Related: math.sin, math.tan

math.cosh( value ) (function)

ID: math.cosh
Group: Math

This function returns hyperbolic cosine of value.

Syntax

math.cosh( value )

Parameters

  • value — int or float, compute the hyperbolic cosine of this number

Returns

Hyperbolic cosine of value

Related: math.sinh, math.tanh

math.deg( value ) (function)

ID: math.deg
Group: Math

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

Syntax

math.deg( value )

Parameters

  • value — int or float, angle in radians to convert to degrees

Returns

Angle specified by value (in radians) in degrees

Related: math.rad

math.rad( value ) (function)

ID: math.rad
Group: Math

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

Syntax

math.rad( value )

Parameters

  • value — int or float, angle in degrees to convert to radians

Returns

Angle specified by value (in degrees) in radians

Related: math.deg

math.exp( value ) (function)

ID: math.exp
Group: Math

This function returns e raised to value

Syntax

math.exp( value )

Parameters

  • value — int or float, exponent of e

Returns

e raised to the power of value

math.floor( value ) (function)

ID: math.floor
Group: Math

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

  • value — int or float, compute the largest integer smaller than or equal to this number

Returns

The largest integer smaller than or equal to value

Related: math.ceil

math.fmod( x, y ) (function)

ID: math.fmod
Group: Math

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

Syntax

math.fmod( x, y )

Parameters

  • x — int or float
  • y — int or float

Returns

The remainder of the division of x by y

Related: math.modf

math.frexp( value ) (function)

ID: math.frexp
Group: Math

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

  • value — int or float

Returns

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

Related: math.ldexp

math.ldexp( m, e ) (function)

ID: math.ldexp
Group: Math

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

Syntax

math.ldexp( m, e )

Parameters

  • m — int or float
  • e — int

Returns

m2^e

Related: math.frexp

math.log( value ) (function)

ID: math.log
Group: Math

This function returns the natural logarithm of value

Syntax

math.log( value )

Parameters

  • value — int or float, compute the natural logarithm of this value

Returns

The natural logarithm of value

Related: math.log10

math.log10( value ) (function)

ID: math.log10
Group: Math

This function returns the base-10 logarithm of value

Syntax

math.log10( value )

Parameters

  • value — int or float, compute the base-10 logarithm of this value

Returns

The base-10 logarithm of value

Related: math.log

math.max( value, ... ) (function)

ID: math.max
Group: Math

This function returns maximum value among its arguments.

Syntax

math.max( value, ... )

Parameters

  • value — any comparable value

Returns

The maximum value among its arguments

Related: math.min

math.min( value, ... ) (function)

ID: math.min
Group: Math

This function returns minimum value among its arguments.

Syntax

math.min( value, ... )

Parameters

  • value — any comparable value

Returns

The minimum value among its arguments

Related: math.max

math.modf( value ) (function)

ID: math.modf
Group: Math

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

Syntax

math.modf( value )

Parameters

  • value — int or float

Returns

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

Related: math.fmod

math.random() (function)

ID: math.random
Group: Math

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

  • minimum — int, minimum value of returned pseudo-random number
  • maximum — int, maximum value of returned pseudo-random number

Returns

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

Related: math.randomseed

math.randomseed( value ) (function)

ID: math.randomseed
Group: Math

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

Syntax

math.randomseed( value )

Parameters

  • value — int, seed of the pseudo-random number generator

Returns

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

Related: math.random

math.sin( value ) (function)

ID: math.sin
Group: Math

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

Syntax

math.sin( value )

Parameters

  • value — int or float, compute the sine of this number

Returns

Sine of value

Related: math.cos, math.tan

math.sinh( value ) (function)

ID: math.sinh
Group: Math

This function returns hyperbolic sine of value.

Syntax

math.sinh( value )

Parameters

  • value — int or float, compute the hyperbolic sine of this number

Returns

Hyperbolic sine of value

Related: math.cosh, math.tanh

math.tan( value ) (function)

ID: math.tan
Group: Math

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

Syntax

math.tan( value )

Parameters

  • value — int or float, compute the tangent of this number

Returns

Tangent of value

Related: math.sin, math.cos

math.tanh( value ) (function)

ID: math.tanh
Group: Math

This function returns hyperbolic tangent of value.

Syntax

math.tanh( value )

Parameters

  • value — int or float, compute the hyperbolic tangent of this number

Returns

Hyperbolic tangent of value

Related: math.sinh, math.cosh

math.sqrt( value ) (function)

ID: math.sqrt
Group: Math

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

  • value — int or float, compute the square root of this number

Returns

Square root of value

Related: math.pow

math.tointeger( value ) (function)

ID: math.tointeger
Group: Math

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

Syntax

math.tointeger( value )

Parameters

  • value — float, value to convert to integer

Returns

value converted to an integer, or nil

Related: math.type

math.type( value ) (function)

ID: math.type
Group: Math

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

Syntax

math.type( value )

Parameters

  • value — int or float, get the type of this value

Returns

"integer" or "float"

Related: math.tointeger

math.ult( m, n ) (function)

ID: math.ult
Group: Math

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

Syntax

math.ult( m, n )

Parameters

  • m — integer, value for m
  • n — integer, value for n

Returns

true if m is below integer n when compared as unsigned

math.huge (const)

ID: math.huge
Group: Math

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 (const)

ID: math.pi
Group: Math

The value of pi.

Syntax

math.pi

Returns

Value of pi

math.maxinteger (const)

ID: math.maxinteger
Group: Math

Specifies an integer with the maximum value for an integer

Syntax

math.maxinteger

Returns

Maximum value for an integer

Related: math.mininteger

math.mininteger (const)

ID: math.mininteger
Group: Math

Specifies an integer with the minimum value for an integer

Syntax

math.mininteger

Returns

Minimum value for an integer

Related: math.maxinteger

objc (property)

ID: objc
Group: Objective-C

Exposes native Objective-C classes.

Native Classes

To access a native Objective-C class, append its name to objc.

-- access the UIScreen class
UIScreen = objc.UIScreen

Constructor

If the native class has a new constructor, you can invoke it directly instead of calling the new method.

-- create an instance of NSDateComponents
dateComponents = objc.NSDateComponents()

Properties

Properties can be read and modified directly.

-- read the screen brightness
brightness = objc.UIScreen.mainScreen.brightness

-- change the screen brightness
objc.UIScreen.mainScreen.brightness = 0.5

Methods

Methods are invoked using the ':' operator and their full selector name, including named arguments separated by underscores '_' instead of colons. Note that the Objective-C method names must always end with an underscore in Codea. The underscores are required for Codea to find the corresponding signatures in Objective-C.

-- Calling a method with multiple arguments
controller:presentViewController_animated_completion_(newController, true, nil)

-- Calling a method with no argument
webView:goBack_()

Callbacks

Callbacks such as completion handlers with up to 7 arguments are supported by passing a function where each parameter is prefixed to indicate the corresponding native type.

The following prefixes are supported for callback arguments:

c: char
i: int, NSInteger
uc: unsigned char
ui: unsigned int, NSUInteger
f: float
d: double, CGFloat
b: bool, BOOL
s: char*
o: NSObject, NSString, etc.

Note that only the first one or two characters are important in your argument names. bGranted and boolGranted will both work for a boolean argument, but for our examples, we decided to go with the second option.

Struct members are passed separately. For example, for an NSRange argument, you could use intLocation and intLength arguments.

Pointers for value types are also supported by prefixing them with p, (e.g. pboolStop). The actual value can be accessed and modified using .value.

Note that when using objc from within a callback, changes are not guaranteed to occur on the main thread. Consider using objc.async inside your callback if you need changes to happen on the main thread, such as modifying UIControls.

Automatic Conversions

Some Codea types will be converted to corresponding Objective types automatically when passed to native methods or properties.

color: UIColor vec2: CGPoint

--- uiView: objc.UIView
uiView.backgroundColor = Color(255, 0, 0)

--- uiTextView: objc.UITextView
uiTextView:setContentOffset_(vec2(0, 100))

Syntax

objc.ClassName

Returns

An intermediary type which can be used to access the native class' properties and methods.

Examples

-- change the screen brightness to 50%
objc.UIScreen.mainScreen.brightness = 0.5
-- request application review
scene = objc.app.keyWindow.windowScene
store = objc.SKStoreReviewController
store:requestReviewInScene_(scene)
-- request notifications permission
center = objc.
  UNUserNotificationCenter.
  currentNotificationCenter
options = objc.enum.UNAuthorizationOptions
center:requestAuthorizationWithOptions_completionHandler_(
  options.badge | options.sound | options.alert,
  function(boolGranted, objError)
    if boolGranted then
      print("granted")
    elseif objError then
      print("error " .. objError.code)
    end
  end)
-- Enumerate words until the word stop is found
txt = "First second stop third fourth"
str = objc.string(txt)
str:enumerateSubstringsInRange_options_usingBlock_(
    objc.range(0, txt:len()),
    objc.enum.NSStringEnumerationOptions.byWords,
    function(objWord,
             isubstringLocation,
             iSubstringLength,
             iEnclosingLocation,
             iEnclosingLength,
             pboolStop)
        if objWord == "stop" then
            pboolStop.value = true
        else
            print(objWord)
        end
    end)

Related: frameworksOverview, objc.enum, objc.delegate, objc.async

objc.delegate (function)

ID: objc.delegate
Group: Objective-C

Returns a type which can be instantiated and used as an Objective-C delegate for the specified type.

Syntax

objc.delegate("DelegateName")

Returns

A type to be used as an Objective-C delegate.

Examples

Delegate = objc.delegate("UITextViewDelegate")

function Delegate:textViewShouldBeginEditing_(objTextView)
  -- replace with false to prevent editing
  return true
end

function Delegate:textViewDidChange_(objTextView)
  print(objTextView.text)
end

-- uiTextView.delegate = Delegate()
-- Exposes the following method to JavaScript:
-- window.webkit.messageHandlers.log.postMessage
Handler = objc.delegate("WKScriptMessageHandler")

function Handler:
  userContentController_didReceiveScriptMessage_(
  objUserContentController, objMessage)
  print(objMessage.body)
end

function setup()
  local ctrl = objc.WKUserContentController()
  local logHandler = Handler()
  ctrl:addScriptMessageHandler_name_(
    logHandler, "log")
end

Related: objc

objc.class (function)

ID: objc.class
Group: Objective-C

Returns a type which can be instantiated and used as an Objective-C class, for example combined with a selector when registering for notifications through the NSNotificationCenter.

Syntax

objc.class("ClassName")

Returns

A type to be used as an Objective-C class.

Examples

NotificationHandler = objc.class("NotificationHandler")

function NotificationHandler:textDidChange(objNotification)
    print(objNotification.object.text)
end

handler = NotificationHandler()

notificationCenter = objc.NSNotificationCenter.defaultCenter
notificationCenter:addObserver_selector_name_object_(
    handler,
    objc.selector("textDidChange"),
    "UITextViewTextDidChangeNotification",
    nil)

Related: objc, objc.selector

objc.selector (function)

ID: objc.selector
Group: Objective-C

Returns an Objective-C selector with the specified name which can be used in combination with an objc.class, for example to register for notifications through the NSNotificationCenter.

Syntax

objc.selector("SelectorName")

Returns

An Objective-C selector (or SEL).

Examples

NotificationHandler = objc.class("NotificationHandler")

function NotificationHandler:textDidChange(objNotification)
    print(objNotification.object.text)
end

handler = NotificationHandler()

notificationCenter = objc.NSNotificationCenter.defaultCenter
notificationCenter:addObserver_selector_name_object_(
    handler,
    objc.selector("textDidChange"),
    "UITextViewTextDidChangeNotification",
    nil)

Related: objc, objc.class

objc.set (function)

ID: objc.set
Group: Objective-C

Returns an Objective-C NSSet initialized from a Lua table.

By default, NSSet returned from calls to Objective-C (or reading properties) are automatically converted to Lua tables. If you need to use the NSSet, you can convert the table to NSSet using objc.set.

Syntax

objc.set({ 1, 2, 3})

Returns

An Objective-C NSSet.

Related: objc

objc.string (function)

ID: objc.string
Group: Objective-C

Returns an Objective-C NSString initialized from a Lua string.

By default, strings returned from calls to Objective-C (or reading properties) are automatically converted to Lua strings and vice versa. If you need to access NSString methods, you can convert the strings to NSString using objc.string.

Syntax

objc.string("Text")

Returns

An Objective-C NSString.

Related: objc

objc.enum (property)

ID: objc.enum
Group: Objective-C

Exposes native Objective-C enumerations.

When value names are prefixed with their enumeration's name, the prefix is removed to simplify their usage.

For example, objc.enum.NLTokenUnit.paragraph is the integer value for NLTokenUnitParagraph (2).

Unnamed enum values can be found directly under objc.enum, e.g. objc.enum.NSUTF8StringEncoding

Syntax

objc.enum.EnumName.ValueName

Returns

A table containing native enumerations and their values.

Examples

-- combine UNAuthorizationOptions options
opts =
  objc.enum.UNAuthorizationOptions.badge |
  objc.enum.UNAuthorizationOptions.sound |
  objc.enum.UNAuthorizationOptions.alert

Related: objc

objc.app (property)

ID: objc.app
Group: Objective-C

The UIApplication's sharedApplication.

Syntax

objc.app

Related: objc, objc.viewer

objc.viewer (property)

ID: objc.viewer
Group: Objective-C

The runtime UIViewController.

Syntax

objc.viewer

Related: objc, objc.app

objc.info (property)

ID: objc.info
Group: Objective-C

Exposes the info dictionary keys and values.

For better readability, all keys have their Apple prefix removed.

For example, to get the value of NSBundleIdentifier, use objc.info.bundleIdentifier.

Syntax

objc.info.Key

Returns

A table containing the info dictionary keys and values.

Examples

-- test if running in an exported project
isStandalone = objc.info.bundleIdentifier ~= "com.twolivesleft.Codify"

Related: objc

objc.insets( top, left, bottom, right ) (function)

ID: objc.insets
Group: Objective-C

Create a UIEdgeInsets.

Syntax

objc.insets( top, left, bottom, right )

Parameters

  • top — top value of the UIEdgeInsets
  • left — left value of the UIEdgeInsets
  • bottom — bottom value of the UIEdgeInsets
  • right — right value of the UIEdgeInsets

objc.log( message ) (function)

ID: objc.log
Group: Objective-C

Log a message using NSLog instead of the Codea console.

Syntax

objc.log( message )

Parameters

  • message — Message to display

objc.inspect( class ) (function)

ID: objc.inspect
Group: Objective-C

Inspect an Objective-C class, listing its variables, properties, methods and protocols.

Returns a table with the following information:

super: the superclass which can be used as if it was accessed through objc

variables: array of instance variables name: name of the variable typeEncoding: see Type Encoding type: user-friendly name of the variable type

properties: array of instance properties name: name of the property attributes: see Property Type String type: user-friendly name of the property type

methods: array of instance methods name: name of the methods returnTypeEncoding: Type Encoding of the method's return value returnType: user-friendly name of the method's return type arguments: array of method arguments name: name of the arguments typeEncoding: see Type Encoding type: user-friendly name of the argument's type

protocols: array of instance protocols name: name of the protocol

Class members are accessible by prefixing with class., for example using objc.inspect(myClass).class.variables to list the class variables of myClass.

Syntax

objc.inspect( class )

Parameters

  • class — Objective-C class to inspect.

Examples

-- inspect the SFSpeechRecognizer class
inspect = objc.inspect(objc.SFSpeechRecognizer)
print("Class has " .. #inspect.methods .. " instance methods.")

objc.async( function ) (function)

ID: objc.async
Group: Objective-C

Calls the function parameter on the main thread asynchronously.

Syntax

objc.async( function )

Parameters

  • function — Parameterless function to run on the main thread.

Related: objc

objc.point( x, y ) (function)

ID: objc.point
Group: Objective-C

Create a CGPoint.

Syntax

objc.point( x, y )

Parameters

  • x — x position of the CGPoint
  • y — y position of the CGPoint

objc.rect( x, y, width, height ) (function)

ID: objc.rect
Group: Objective-C

Create a CGRect.

Syntax

objc.rect( x, y, width, height )

Parameters

  • x — x position of the CGRect
  • y — y position of the CGRect
  • width — width of the CGRect
  • height — height of the CGRect

objc.size( width, height ) (function)

ID: objc.size
Group: Objective-C

Create a CGSize.

Syntax

objc.size( width, height )

Parameters

  • width — width of the CGSize
  • height — height of the CGSize

objc.range( loc, len ) (function)

ID: objc.range
Group: Objective-C

Create a NSRange.

Syntax

objc.range( loc, len )

Parameters

  • loc — location of the NSRange
  • len — length of the NSRange

objc.color( r, g, b, a ) (function)

ID: objc.color
Group: Objective-C

Create a CGColor. For UIColor, use the Codea Color type instead.

Syntax

objc.color( r, g, b, a )

Parameters

  • r — red value of the CGColor
  • g — green value of the CGColor
  • b — blue value of the CGColor
  • a — alpha value of the CGColor

objc.vector( dx, dy ) (function)

ID: objc.vector
Group: Objective-C

Create a CGVector.

Syntax

objc.vector( dx, dy )

Parameters

  • dx — x direction of the CGVector
  • dy — y direction of the CGVector

objc.affineTransform( a, b, c, d, tx, ty ) (function)

ID: objc.affineTransform
Group: Objective-C

Create a CGAffineTransform.

Syntax

objc.affineTransform( a, b, c, d, tx, ty )

Parameters

  • a — a value of the CGAffineTransform
  • b — b value of the CGAffineTransform
  • c — c value of the CGAffineTransform
  • d — d value of the CGAffineTransform
  • tx — tx value of the CGAffineTransform
  • ty — ty value of the CGAffineTransform

Frameworks (overview)

ID: frameworksOverview
Group: Objective-C

Here are some of the frameworks included with the Codea runtime.

Refer to Apple's documentation for how to interact with them.

ARKit AssetsLibrary AudioKit AudioToolbox AuthenticationServices CFNetwork CoreBluetooth CoreGraphics CoreHaptics CoreLocation CoreMedia CoreMIDI CoreML CoreMotion CoreText CoreVideo FileProvider GameController GameplayKit GLKit JavaScriptCore MapKit MediaPlayer MessageUI MLCompute NaturalLanguage OpenGLES PDFKit PencilKit ReplayKit Social Speech UIKit UserNotifications WebKit

For a more exhaustive list, use the example code below.

Examples

-- list all included system Frameworks
local bundles = objc.NSBundle.allFrameworks
local systemBundles = {}

for i, b in ipairs(bundles) do
  if string.find(
      b.bundlePath,
      "System/Library/Frameworks/") then
      table.insert(systemBundles, b.bundlePath)
  end
end

table.sort(systemBundles)

for i, bundle in ipairs(systemBundles) do
  print(bundle)
end

Related: objc

openURL( url ) (function)

ID: openURL
Group: Opening Links

This function opens the URL specified by url. By default the URL will open in an external browser. Specifying true for the internal parameter will open the URL using an in-app browser.

Syntax

openURL( url )
openURL( url, internal )

Parameters

  • url — string, the url to open
  • internal — boolean, open the url in an internal browser

Examples

function touched(touch)
    openURL( 'http://twolivesleft.com' )
end
function touched(touch)
    -- Open in-app browser
    openURL( 'http://twolivesleft.com', true )
end

HTTP Callback Overview (overview)

ID: httpCallbackOverview
Group: HTTP Requests

HTTP requests are handled by the http.request 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.request 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: http.request, image

http.request( url, successFunction ) (function)

ID: http.request
Group: HTTP Requests

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.request 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.request( url, successFunction )
http.request( url, successFunction,
                   failFunction )
http.request( url, success, fail,
              parameterTable )

Parameters

  • url — string, the url to submit the request

  • successFunction — function, the function to be called when the request succeeds. This function will be called with an argument representing the returned data.

  • failFunction — function, the function to be called when the request fails. This function will be called with a string argument containing the error.

  • parameterTable — table, specifying advanced parameters "method" : "HEAD", "GET", "PUT", "POST", "DELETE"

    "headers" : table, string pairs for name and value of HTTP headers

    "data" : string, POST data. Only used for POST or PUT methods.

    "useragent" : string

Examples

-- Downloading data
function setup()
    --   Request some data
    http.request( 'http://twolivesleft.com/hello.txt',
                  didGetData, didNotGetData )
end

-- Our callback function
function didGetData( data, status, headers )
    print( status..' : '..data )
end

-- Our failure function
function didNotGetData( error )
    print( "Failed to get data. Error:" )
    print( error )
end
-- Downloading an image
function setup()
    logoImage = nil

    -- Request some data
    http.request( '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

Related: httpCallbackOverview, image

OSC Overview (overview)

ID: oscOverview
Group: Open Sound Control (OSC)

Open Sound Control is a protocol for networking computers and multimedia devices. This module allows you to start an OSC server and send messages to an OSC server.

Starting an OSC server is handled by osc.start(port), which returns the IP address of the started server.

Clients can be configured to send messages to a server by setting the osc.host and osc.port properties. And then calling the osc.send() function.

OSC messages are composed of an array of numbers, strings or integers and sent to an address (e.g., "/Test"). You can listen for OSC messages by starting a server and implementing the function osc.listen(address, ...).

-- OSC listen function
function osc.listen(address, ...)

Related: osc, osc.start, osc.stop, osc.send, osc.listen

osc (type)

ID: osc
Group: Open Sound Control (OSC)

This module contains the functions and parameters necessary to configure, send and receive messages via OSC.

Parameters

  • port — int, the port used by the osc.send function
  • host — string, the host or IP address used by the osc.send function
  • listen — function, set this to the function you would like to use to handle incoming messages

Related: oscOverview, osc.start, osc.stop, osc.send, osc.listen

osc.start (function)

ID: osc.start
Group: Open Sound Control (OSC)

Starts the OSC server on the specified port. If the server started successfully, returns the local address of the server.

Syntax

local host = osc.start(9000)

Parameters

  • port — int, the port on which to start the OSC server. Defaults to 9000

Returns

string, the host on which the server is running or nil if the server failed to start

Examples

function setup()
    local host = osc.start(9000)

    print("Server running at: ", host)
end

Related: osc.stop, osc.listen, osc, oscOverview, osc.send

osc.stop (function)

ID: osc.stop
Group: Open Sound Control (OSC)

Stops the OSC server.

Syntax

osc.stop()

Related: osc.start

osc.listen (function)

ID: osc.listen
Group: Open Sound Control (OSC)

You do not call this function. Instead you can either assign a function to osc.listen or declare a global Lua function named osc.listen. If this function exists, and an OSC server has been started using osc.start, then this function will be called whenever messages are received.

This function accepts a variable number of arguments because OSC messages can contain an arbitrary number of elements. See the examples for how to declare this function.

Syntax

function osc.listen(address, ...)

Examples

function osc.listen(address, ...)
    print(address)

    for _,v in pairs({...}) do
        print(v)
    end
end
-- This is equivalent to the first example
osc.listen = function(address, ...)
    print(address)

    for _,v in pairs({...}) do
        print(v)
    end
end

Related: osc.start, oscOverview

osc.send (function)

ID: osc.send
Group: Open Sound Control (OSC)

Sends a message to the server running at osc.host on osc.port. This function accepts an address and a variable number of arguments (which can be string, number, or integer).

Syntax

osc.send(address, ...)

Parameters

  • address — string, the OSC address to send the message to
  • ... — varied, any number of integers, strings or numbers to send

Examples

-- Where the server is running
osc.host = "localhost"
osc.port = 9000

-- Send some messages
osc.send("/", 1, "Hello", 4.5)

osc.send("/Address", 10.0, 5.0)

osc.send("/Address")

Related: osc, oscOverview

parameter.number( name, min, max ) (function)

ID: parameter.number
Group: Creating Parameters

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

The optional callback argument specifies a callback function to be called when the parameter slider changes. This callback function is provided the parameter's value as its single argument.

Syntax

parameter.number( name )
parameter.number( name, min, max )
parameter.number( name, min, max, initial )
parameter.number( name, min, max, initial, callback )

Parameters

  • name — string, the parameter function will create a global variable with this name
  • min — number, specifies the minimum value that your parameter can take
  • max — number, specifies the maximum value that your parameter can take
  • initial — number, specifies the initial, or starting, value of the parameter
  • callback — function, this function will be called whenever the parameter is changed, it will be given the parameter value as an argument

Examples

function setup()
    --Creates a global variable called Radius
    parameter.number("Radius", 50.0, 300.0, 100.0)
end

function draw()
    background(128)
    ellipseMode(RADIUS)
    ellipse(WIDTH/2, HEIGHT/2, Radius)
end

Related: parameter.integer, parameter.text, parameter.color, parameter.boolean, parameter.action, parameter.clear

parameter.integer( name, min, max ) (function)

ID: parameter.integer
Group: Creating Parameters

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.number() 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 parameter.integer() 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].

The optional callback argument specifies a callback function to be called when the parameter slider changes. This callback function is provided the parameter's value as its single argument.

Syntax

parameter.integer( name )
parameter.integer( name, min, max )
parameter.integer( name, min, max, initial )
parameter.integer( name, min, max, initial, callback )

Parameters

  • name — string, the parameter.integer function will create a global variable with this name
  • min — int, specifies the minimum value that your parameter can take
  • max — int, specifies the maximum value that your parameter can take
  • initial — int, specifies the initial, or starting, value of the parameter
  • callback — function, this function will be called whenever the parameter is changed, it will be given the parameter value as an argument

Examples

function setup()
    --Creates a global variable called Radius
    -- It also has a callback that prints the
    -- value when changed
    parameter("Radius", 50, 300, 100,
      function(x) print(x) end )
end

function draw()
    background(128)
    ellipseMode(RADIUS)
    ellipse(WIDTH/2, HEIGHT/2, Radius)
end

Related: parameter.number, parameter.text, parameter.color, parameter.boolean, parameter.action, parameter.clear

parameter.color( name, color ) (function)

ID: parameter.color
Group: Creating Parameters

This function creates a visual color sample in the viewer that can be used to adjust a global color variable in your code.

You generally call the parameter.color() function in the setup() function of your main file. The string you specify for name will be exposed as a global variable of the color type.

This can be used in your code. When you tap the color sample in the viewer, an interactive color picker will be presented, allowing you to adjust the variable live, while your code is running.

You may also set the initial value of the color with either a color object, a gray scale value, or an rgb triplet (you may include an alpha value as well).

The optional callback argument specifies a callback function to be called when the color value changes. This callback function is provided a single argument, of the color type, containing the new value.

Syntax

parameter.color( name )
parameter.color( name, color )
parameter.color( name, color, callback )

parameter.color( name )
parameter.color( name, red, green, blue )
parameter.color( name, red, green, blue, callback )

parameter.color( name )
parameter.color( name, red, green, blue, alpha )
parameter.color( name, red, green, blue, alpha, callback )

parameter.color( name )
parameter.color( name, gray )
parameter.color( name, gray, callback )

parameter.color( name )
parameter.color( name, gray, alpha )
parameter.color( name, gray, alpha, callback )

Parameters

  • name — string, the parameter function will create a global color variable with this name
  • red — int, specifies the initial value of the red component of the color
  • green — int, specifies the initial value of the green component of the color
  • blue — int, specifies the initial value of the blue component of the color
  • gray — int, specifies the gray value of the color
  • alpha — int, specifies the initial value of the alpha component of the color
  • callback — function, this function will be called whenever the parameter is changed, it will be given the new color value as an argument

Examples

function setup()
    --Creates a global color variable called FillColor
    -- make it red by default
    parameter.color("FillColor", 255, 0, 0)

    --Creates a global color varialbe called StrokeColor
    -- make it white by default
    parameter.color("StrokeColor", color(255))
end

function draw()
    background(128)

    strokeWidth(10)

    --Set our colors using the parameter values
    stroke(StrokeColor)
    fill(FillColor)

    ellipse(WIDTH/2, HEIGHT/2, 300)
end

Related: color, parameter.integer, parameter.text, parameter.number, parameter.boolean, parameter.action, parameter.clear

parameter.clear() (function)

ID: parameter.clear
Group: Clearing the Parameter List

This function clears the parameter list of all parameter widgets and watch values. You can then re-add parameters using the parameter group of functions.

Syntax

parameter.clear()

Related: parameter.number, parameter.integer, parameter.color, parameter.action, parameter.boolean, parameter.watch, output.clear

parameter.boolean( name, initial ) (function)

ID: parameter.boolean
Group: Creating Parameters

This function creates a visual switch in the viewer that can be used to adjust a boolean variable in your code.

You generally call the parameter.boolean() 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 switch in the viewer, the variable will be set appropriately. You may also specify an initial value for the switch. With true causing the switch to be set to the ON state, and false setting the switch to the OFF state.

The optional callback argument specifies a callback function to be called when the parameter switch changes. This callback function is provided the parameter's value as its single argument.

Syntax

parameter.boolean( name )
parameter.boolean( name, initial )
parameter.boolean( name, initial, callback )
parameter.boolean( name, callback )

Parameters

  • name — string, the parameter function will create a global variable with this name
  • initial — boolean, specifies the initial value of the boolean parameter
  • callback — function, this function will be called whenever the parameter is changed, it will be given the parameter value as an argument

Examples

function setup()
    -- Creates a simple switch that prints when changed
    parameter.boolean("MySwitch", true, switchChanged)
end

function switchChanged( value )
    print( "MySwitch changed to " .. tostring(value) )
end

Related: parameter.integer, parameter.text, parameter.color, parameter.number, parameter.action, parameter.clear

parameter.text( name, initial ) (function)

ID: parameter.text
Group: Creating Parameters

This function creates a visual text box in the viewer. You can type in this control to adjust the contents of the corresponding string value defined by name.

You generally call the parameter.text() 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 input text in the parameter.text control, the variable defined by name will be set appropriately. You may also specify the initial contents of the text variable by setting initial to a string.

The optional callback argument specifies a callback function to be called when the parameter text changes. This callback function is provided the parameter's value as its single argument.

Syntax

parameter.text( name )
parameter.text( name, initial )
parameter.text( name, initial, callback )
parameter.text( name, callback )

Parameters

  • name — string, the parameter function will create a global variable with this name
  • initial — string, specifies the initial value of the text parameter
  • callback — function, this function will be called whenever the parameter is changed, it will be given the parameter value as an argument

Examples

function setup()
    -- Creates a simple switch that prints when changed
    parameter.text("MyText", "Hello World!", textChanged)
end

-- Print our text parameter in upper-case
function textChanged( value )
    print( string.upper(value) )
end

Related: parameter.integer, parameter.boolean, parameter.color, parameter.number, parameter.action, parameter.clear

parameter.action( name, callback ) (function)

ID: parameter.action
Group: Creating Parameters

This function creates a visual button in the viewer sidebar. Pressing the button will call the function defined by callback. The name argument sets the label of the button.

You generally call the parameter.action() function in the setup() function of your main file. The string you specify for name will be used to label the button that appears in the viewer. It will not be exposed as a global variable.

The callback argument specifies a callback function to be called when the button is pressed. It is passed the name of the button as its only argument.

Syntax

parameter.action( name, callback )

Parameters

  • name — string, the parameter function will create a global variable with this name
  • callback — function, this function will be called whenever the parameter is changed, it will be given the parameter value as an argument

Examples

function setup()
    -- Creates a button to clear the output
    parameter.action("Clear Output", output.clear)
end

Related: parameter.integer, parameter.boolean, parameter.color, parameter.number, parameter.text, parameter.clear

output.clear() (function)

ID: output.clear
Group: Clearing the Parameter List

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

Syntax

output.clear()

physics.body (type)

ID: physics.body
Group: Creating Bodies

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

  • type — int, the type of the body, can be STATIC, DYNAMIC or KINEMATIC
  • shapeType — readonly, the shape type of the body, can be CIRCLE, POLYGON, CHAIN or EDGE
  • radius — float, the radius of the body, only valid for circle shape types
  • points — table, a table containing the points that make up the body, only valid for polygon shape types
  • x — float, the x position of the body in pixels
  • y — float, the y position of the body in pixels
  • position — vec2, the position of the body
  • angle — float, the angle of the body in degrees
  • worldCenter — vec2, the center of mass of the body in world space
  • localCenter — vec2, the center of mass of the body in local space
  • linearVelocity — vec2, the current linear velocity of the body in pixels per second
  • angularVelocity — float, the angular velocity of the body in degrees per second
  • density — float, the density of the body in kg/m^2, 1 by default, cannot be negative
  • mass — float, the mass of the body in kg, cannot be negative. If you set this, density will be ignored
  • inertia — float, the moment of inertia of the body. Cannot be set
  • restitution — float, the restitution, or 'bouncyness' of the body
  • friction — float, the friction of the body determines how easy the object slides. This defaults to 0.2.
  • categories — table, an array of the categories (1 to 16) to which the body belongs to for collision filtering. The default is {1}.
  • mask — table, an array of the categories of bodies with which the body will collide. The default is all categories, {1, 2, ..., 15, 16}.
  • fixedRotation — boolean, locks the rotation of this body
  • active — boolean, set to false to remove from simulation
  • sensor — boolean, whether the body is a sensor. Collision information is generated for sensors, but they do not physically affect the scene.
  • awake — boolean, true if body is currently awake, false otherwise
  • sleepingAllowed — boolean, set to false to prevent bodies from sleeping (default: true)
  • bullet — boolean, set to true for fast moving bodies to prevent tunneling
  • gravityScale — float, controls the influence of gravity on this body, 1 by default
  • linearDamping — float, the amount of linear damping applied to this body. Damping reduces the world velocity of bodies, and is different from friction in that it occurs regardless of contact.
  • angularDamping — float, the amount of angular damping applied to this body.
  • interpolate — boolean, controls render interpolation, used to smooth out motion but introduces slight lag
  • joints — table, returns the list of joints connected to this body
  • info — value, used for storing arbitrary data in this body

Examples

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

Related: physics.joint

CIRCLE (const)

ID: CIRCLE
Group: Creating Bodies

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: physics.body

POLYGON (const)

ID: POLYGON
Group: Creating Bodies

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: physics.body

CHAIN (const)

ID: CHAIN
Group: Creating Bodies

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: physics.body

EDGE (const)

ID: EDGE
Group: Creating Bodies

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: physics.body

DYNAMIC (const)

ID: DYNAMIC
Group: Creating Bodies

This constant specifies the dynamic body type.Dynamic bodies move under the influence of collisions, forces, joints and gravity.

Syntax

DYNAMIC

Returns

int

Related: physics.body

STATIC (const)

ID: STATIC
Group: Creating Bodies

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: physics.body

KINEMATIC (const)

ID: KINEMATIC
Group: Creating Bodies

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: physics.body

physics.joint (type)

ID: physics.joint
Group: Attaching Bodies with Joints

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

Syntax

physics.joint( REVOLUTE, bodyA, bodyB,
                         anchor )

physics.joint( PRISMATIC, bodyA, bodyB,
                          anchorA,
                          direction )

physics.joint( DISTANCE, bodyA, bodyB,
                         anchorA,
                         anchorB )

physics.joint( WELD, bodyA, bodyB,
                            anchor )

physics.joint( ROPE, bodyA, bodyB,
                         anchorA,
                         anchorB,
                         maxLength )

Parameters

  • type — int, the type of the joint, can be REVOLUTE, DISTANCE, PRISMATIC, WELD or ROPE
  • bodyA — body, the first body attached to this joint
  • bodyB — body, the second body attached to this joint
  • anchorA — vec2, the anchor for the first body in world coordinates
  • anchorB — vec2, the anchor for the second body in world coordinates
  • reactionForce — vec2, the current amount of force used by the joint to constrain the relative motion between the two bodies. This can be used to break joints when the force reaches a given threshold
  • reactionTorque — float, the current amount of torque used by the joint to constrain the relative rotation between the two bodies. This can be used to break joints when the torque reaches a given threshold
  • enableLimit — boolean, whether or not the limit for this joint is enabled. Only certain joints, such as REVOLUTE and PRISMATIC have limits
  • lowerLimit — float, the lower limit of this joint. For REVOLUTE joints this represents the angular limit between bodies in degrees. For PRISMATIC joints this represents the translation limit
  • upperLimit — float, the upper limit of this joint. For REVOLUTE joints this represents the angular limit between bodies in degrees. For PRISMATIC joints this represents the translation limit
  • enableMotor — boolean, whether or not the motor for this joint is enabled. Only certain joints, such as REVOLUTE and PRISMATIC have motors
  • motorSpeed — float, the desired speed of the motor. For REVOLUTE joints this is in degrees per second. For PRISMATIC joints this is specified in pixels per second
  • maxMotorTorque — float, the maximum amount of torque the motor can apply to reach the desired motor speed. Only REVOLUTE joints have this property
  • maxMotorForce — float, the maximum amount of force the motor can apply to reach the desired motor speed. Only PRISMATIC joints have this property
  • length — float, the length of the joint. Only applies to DISTANCE joints
  • frequency — float, The softness of the joint, set to zero for stiff joints. Only applies to DISTANCE and WELD joints
  • dampingRatio — float, Controls the damping of soft joints, higher values reduce oscillation, set to zero for stiff joints. Only applies to DISTANCE and WELD joints
  • maxLength — float, Controls the maximum length (distance between anchor points) of the joint. Only applies to ROPE joints

Related: physics.body

REVOLUTE (const)

ID: REVOLUTE
Group: Attaching Bodies with Joints

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: physics.joint

DISTANCE (const)

ID: DISTANCE
Group: Attaching Bodies with Joints

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: physics.joint

PRISMATIC (const)

ID: PRISMATIC
Group: Attaching Bodies with Joints

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: physics.joint

WELD (const)

ID: WELD
Group: Attaching Bodies with Joints

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: physics.joint

ROPE (const)

ID: ROPE
Group: Attaching Bodies with Joints

This constant specifies the rope joint type. Rope joints constrain the maximum distance between two bodies.

Syntax

ROPE

Returns

int

Related: physics.joint

Contacts Overview (overview)

ID: contactsOverview
Group: Handling Contacts Between Bodies

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

physics.contact (type)

ID: physics.contact
Group: Handling Contacts Between Bodies

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.

Parameters

  • id — number, a unique id that represents this contact
  • state — int, the current state of this contact, can be BEGAN, CHANGED, ENDED
  • touching — bool, whether or not the contact is currently touching. Due to the way contacts are cached this can be false under some circumstances.
  • position — vec2, the current position of this contact
  • normal — vec2, the current normal of this contact
  • normalImpulse — float, the magnitude of energy used to separate the two colliding bodies projected along the normal vector. Useful for measuring the strength of an impact
  • tangentImpulse — float, the magnitude of energy used to separate the two colliding bodies projected along the tangent vector (perpendicular to the normal). Useful for measuring the friction of an impact
  • pointCount — int, the number of points in the contact manifold
  • points — table, an array of vec2's describing the contact manifold
  • bodyA — body, the first body in the collision represented by this contact
  • bodyB — body, the second body in the collision represented by this contact

Examples

function collide(contact)
    if contact.state == BEGAN then
        print("HIT!")
    end
end

Related: physics.body, physics.joint

body.applyForce( force ) (method)

ID: body.applyForce
Group: Creating Bodies

Applies a force to this body object. If worldPoint is not specified then the force will be applied to the center of the body.

Syntax

myBody:applyForce( force )
myBody:applyForce( force, worldPoint )

Parameters

  • force — vec2, the amount of force to apply as a vector
  • worldPoint — vec2, the point to apply the force from, in world coordinates

Related: physics.body, body.applyTorque

body.applyTorque( torque ) (method)

ID: body.applyTorque
Group: Creating Bodies

Applies torque to this body object.

Syntax

myBody:applyTorque( applyTorque )

Parameters

  • torque — float, the amount of torque

Related: physics.body, body.applyForce

body.applyLinearImpulse( impulse ) (method)

ID: body.applyLinearImpulse
Group: Creating Bodies

Applies a linear impulse to this body object. If worldPoint is not specified then the impulse will apply to the center of the body.

Syntax

myBody:applyLinearImpulse( impulse )
myBody:applyLinearImpulse( impulse, worldPoint )

Parameters

  • impulse — vec2, the impulse to apply as a vector
  • worldPoint — vec2, the point to apply the impulse from, in world coordinates

Related: physics.body, body.applyAngularImpulse

body.applyAngularImpulse( impulse ) (method)

ID: body.applyAngularImpulse
Group: Creating Bodies

Applies an angular impulse to this body object.

Syntax

myBody:applyAngularImpulse( impulse )

Parameters

  • impulse — float, the angular impulse

Related: physics.body, body.applyLinearImpulse

body.destroy() (method)

ID: body.destroy
Group: Creating Bodies

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

Examples

-- destroy should be used before
-- setting a body to nil
circle = physics.body(CIRCLE, 100)
circle:destroy()
circle = nil

Related: physics.body, body.applyForce, body.destroy

body.testPoint( worldPoint ) (method)

ID: body.testPoint
Group: Creating Bodies

Tests if worldPoint is inside this body.

Syntax

myBody:testPoint( worldPoint )

Parameters

  • worldPoint — vec2, the point to test for intersection, in world space

Returns

true if worldPoint is inside this body, false otherwise

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

Related: physics.body, body.applyForce, body.destroy, body.testPoint

body.testOverlap( otherBody ) (method)

ID: body.testOverlap
Group: Creating Bodies

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

myBody:testOverlap( otherBody )

Parameters

  • otherBody — body, the body to test for intersection with

Returns

true if this body is intersecting with otherBody, false otherwise

Examples

-- test if two bodies overlap
circle1 = physics.body(CIRCLE, 100)
circle2 = physics.body(CIRCLE, 10)

if circle1:testOverlap(circle2) then
    print("HIT!")
end

Related: physics.body, body.applyForce, body.destroy, body.testPoint

body.getLocalPoint( worldPoint ) (method)

ID: body.getLocalPoint
Group: Creating Bodies

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: physics.body, body.applyForce, body.destroy, body.testPoint

body.getWorldPoint( localPoint ) (method)

ID: body.getWorldPoint
Group: Creating Bodies

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: physics.body, body.applyForce, body.destroy, body.testPoint

body.getLinearVelocityFromWorldPoint( point ) (method)

ID: body.getLinearVelocityFromWorldPoint
Group: Creating Bodies

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: physics.body, body.applyForce, body.destroy, body.testPoint

body.getLinearVelocityFromLocalPoint( point ) (method)

ID: body.getLinearVelocityFromLocalPoint
Group: Creating Bodies

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: physics.body, body.applyForce, body.destroy, body.testPoint

physics.pause() (function)

ID: physics.pause
Group: Physics Simulation Functions

Pauses the physics simulation.

Syntax

-- pause physics
physics.pause()

Related: physics.resume

physics.resume() (function)

ID: physics.resume
Group: Physics Simulation Functions

Resumes the physics simulation.

Syntax

-- resume physics
physics.resume()

Related: physics.pause

physics.raycast( start, end, ... ) (function)

ID: physics.raycast
Group: Physics Simulation Functions

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

  • start — vec2, the start point of the ray (technically a line segment, but finite for practical purposes)
  • end — vec2, the end point of the ray

Returns

table, if the raycast intersects a body this function will return a table containing the following key-value pairs:

body => detected
point => point of intersection
normal => normal on surface of hit body
fraction => fraction of total ray length from start to intersecton point

Related: physics.raycastAll, physics.queryAABB

physics.raycastAll( start, end, ... ) (function)

ID: physics.raycastAll
Group: Physics Simulation Functions

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

  • start — vec2, the start point of the ray (technically a line segment, but finite for practical purposes)
  • end — vec2, the end point of the ray

Returns

array, if the raycast intersects one or more bodies this function will an array of tables containing the following key-value pairs

body => detected body
point => point of intersection
normal => normal on surface of hit body
fraction => fraction of total ray length from start to intersecton point

Related: physics.raycast, physics.queryAABB

physics.queryAABB( lowerLeft, upperRight, ... ) (function)

ID: physics.queryAABB
Group: Physics Simulation Functions

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

  • lowerLeft — vec2, the position of the lower left corner of the query axis-aligned bounding box
  • upperRight — vec2, the position of the upper right corner of the query axis-aligned bounding box

Returns

array, returns all bodies that lie within the supplied bounding box

Related: physics.raycast, physics.raycastAll, physics.queryAABB

physics.gravity( x, y ) (function)

ID: physics.gravity
Group: Physics Simulation Functions

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()
physics.gravity( x, y )
physics.gravity( grav )
physics.gravity( Gravity )

Parameters

  • x — float, gravity in the x-axis
  • y — float, gravity in the y-axis
  • grav — vec2, gravity in both axes
  • Gravity — vec3, device gravity used as a special case

Returns

vec2, the current world gravity if no parameters are supplied

Related: physics.iterations, physics.pixelToMeterRatio

physics.iterations( velIterations, posIterations ) (function)

ID: physics.iterations
Group: Physics Simulation Functions

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

  • velocityIterations — int, the number of velocity iterations performed each time step (default: 10)
  • positionIterations — int, the number of position iterations performed each time step (default: 8)

Related: physics.gravity, physics.pixelToMeterRatio

physics.timeStep( timeStep ) (function)

ID: physics.timeStep
Group: Physics Simulation Functions

Sets the time step of the world, units are in seconds. Default is 1/60. When no parameters are passed, function returns current time step as a float.

Syntax

physics.timeStep()
physics.timeStep( timeStep )

Parameters

  • timeStep — float, time step in seconds

Returns

float, the current time step if no parameters are supplied

Related: physics.iterations

physics.pixelToMeterRatio (const)

ID: physics.pixelToMeterRatio
Group: Physics Simulation Functions

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.

Syntax

ratio = physics.pixelToMeterRatio
physics.pixelToMeterRatio = ratio

Returns

int, the current ratio

Related: physics.gravity, physics.iterations

physics.continous (const)

ID: physics.continuous
Group: Physics Simulation Functions

Sets whether the physics engine performs continuous collision detection. Continuous collision detection ensures that very fast moving bodies do not pass through thin objects.

You must also set the bullet property to true on any physics body you wish to use with continuous collision detection.

By default, this value is false because continuous physics increases the computational cost of running the physics engine.

Syntax

physics.continuous = true

Returns

bool, whether continous collision is set

Related: physics.body

physics.bodies (property)

ID: physics.bodies
Group: Creating Bodies

Gets a read-only list of all active bodies.

Syntax

bodies = physics.bodies

Examples

-- destroy all static bodies
for i, b in ipairs(physics.bodies) do
  if b.type == STATIC then
      b:destroy()
  end
end

Related: physics.body

Mesh Overview (overview)

ID: meshOverview
Group: Overview

Meshes in Codea can be used to efficiently render 2D shapes and 3D models. The mesh object type represents a triangle mesh — a collection of vertex triplets that each represent a triangle. Each vertex in a mesh contains a position (vec2 or vec3), texture coordinate (vec2), and color (color).

To create a mesh, call the mesh() function:

myMesh = mesh()

A mesh object has the following settable properties:

myMesh.texture   -- sprite string or image
myMesh.vertices  -- table of vertices (vec2 or vec3)
myMesh.texCoords -- table of texture coordinates (vec2)
myMesh.colors    -- table of colors (color)
myMesh.normals   -- table of normals (vec3)
myMesh.shader    -- a shader object

Texture coordinates — the texCoords property — define a mapping between a 2D coordinate within a texture (ranging from 0,0 to 1,1) and a vertex in your mesh. This allows you to specify which portions of an image cover the triangles in your mesh.

Vertex colors define the color at a particular vertex in your mesh. These colors are linearly interpolated between vertices. This allows you to smoothly blend between colors at neighbouring vertices.

normals can be used to define 3D normals for each vertex in your mesh. This is useful for computing shading from light sources. By default, Codea does not use mesh normals in any of its rendering modes. However, you may use the normal buffer in your own custom shaders.

The mesh type also contains convenience methods, such as addRect, for quickly adding rectangles to a mesh. Please see the related documentation for more details.

The shader property is discussed in more detail in the shaders section. This property can be used to link a shader with a mesh for advanced rendering.

Examples

-- Create a mesh
myMesh = mesh()

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

-- Assign texture coordinates
myMesh.texCoords = {vec2(0,0),
                    vec2(1,0),
                    vec2(1,1)}

-- Assign a texture
myMesh.texture = asset.Planet_Cute.Grass_Block

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

-- Draw the mesh
myMesh:draw()

Related: mesh, vec3, vec2, color, mesh.draw, shaderOverview

Shader Overview (overview)

ID: shaderOverview
Group: Overview

Shaders in Codea are used only in conjunction with mesh. They can be used to render special effects, deformations, lighting and other advanced graphical effects when drawing a mesh.

Shaders are written in a language called GLSL ES. This is the OpenGL ES Shading Language. Codea includes a special editor called the Shader Lab for writing shaders.

In order to use shaders within Codea you use the shader object type. To create a shader, use the following syntax:

myMesh.shader = shader(asset.documents.MyShader)

(Note that you can tap on the highlighted shader parameters in the code editor to select, or even create new shaders directly within the Codea editor.)

This will load the file "MyShader" in your Documents and attach it to myMesh. Any uniform variables declared in your shader can then by accessed as properties on your shader as follows:

-- Assume MyShader declares a float
--  uniform called "myCustomUniform"
myMesh.shader.myCustomUniform = 3.5

Similarly, attribute variables declared in your shader can be accessed as buffers on your mesh:

-- Assume MyShader declares a vec2
--  attribute called "myAttribute"
buf = myMesh:buffer("myAttribute")
buf:resize(10)
buf[1] = vec2(1,1)
buf[2] = vec2(0,1)
...

For advanced users, you can also bypass the shader picking system and Shader Lab by setting your GLSL code directly on your shader object. For example, you may do the following:

myShader.vertexProgram = "... vertex program string ..."
myShader.fragmentProgram = "... fragment program string ..."

Examples

-- Create a mesh
myMesh = mesh()

-- Assign a shader
myMesh.shader = shader(asset.documents.MyShader)

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

-- Assign texture coordinates
myMesh.texCoords = {vec2(0,0),
                    vec2(1,0),
                    vec2(1,1)}

-- Assign a texture
myMesh.texture = asset.builtin.Planet_Cute.Grass_Block

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

-- Draw the mesh
myMesh:draw()

Related: shader, mesh, buffer, mesh.buffer, meshOverview

mesh (type)

ID: mesh
Group: Meshes

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, or using the CAMERA constant to use the current live camera capture source.

Syntax

m = mesh()

Parameters

  • vertices — table, an array of vec2 or vec3 objects
  • colors — table, an array of color objects. If not set the global fill color is used for all vertices
  • texCoords — table, an array of vec2 objects. If not set, triangles are drawn with color only
  • texture — string, image or CAMERA, the texture to use when drawing this mesh. If not set, triangles are drawn with color only
  • normals — table, an array of vec3 objects. Not used by mesh, but may be used by custom shaders.
  • shader — shader, a shader object
  • valid — bool, true if this mesh is valid for drawing
  • size — int, number of vertices in this mesh

Returns

The newly created empty mesh

Examples

-- Create a mesh
myMesh = mesh()

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

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

Related: color, image, spriteSize, sprite, vec3, vec2, CAMERA, shader, meshOverview, shaderOverview

mesh.draw() (method)

ID: mesh.draw
Group: Meshes

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

The count parameter specifies the number of instances of this mesh to draw. This is an advanced parameter and can be used with instanced mesh buffers and shaders to efficiently draw many copies of the same mesh differentiated via shader attributes and uniforms.

The count parameter is only available on devices which support mesh instancing. Older devices may not support this parameter and will ignore it.

Syntax

myMesh:draw()
myMesh:draw(count)

Parameters

  • count — integer, number of instances of this mesh to draw

Related: mesh

mesh.setColors( c ) (method)

ID: mesh.setColors
Group: Meshes

This method sets the colors of all vertices in the mesh to the color specified by c (or r,g,b,a).

Syntax

myMesh:setColors( c )
myMesh:setColors( r, g, b )
myMesh:setColors( r, g, b, a )

Parameters

  • c — color, set all mesh vertices to this color
  • r — value of the red color component to apply to all vertices
  • g — value of the green color component to apply to all vertices
  • b — value of the blue color component to apply to all vertices
  • a — value of the alpha component to apply to all vertices

Related: mesh

mesh.clear() (method)

ID: mesh.clear
Group: Meshes

This method clears a mesh removing all vertices, texCoords, colors and normals. The underlying capacity of the mesh remains after clearing and this may be preferable to creating a new mesh. This method also clears any custom buffers attached to the mesh through shaders.

Syntax

myMesh:clear()

Related: mesh

mesh.addRect( x, y, w, h, r ) (method)

ID: mesh.addRect
Group: Meshes

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

  • x — float, the x coordinate used to place the rectangle
  • y — float, the y coordinate used to place the rectangle
  • w — float, the width of the rectangle
  • h — float, the height of the rectangle
  • r — float, the rotation of the rectangle

Returns

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

Related: mesh, mesh.setRect

mesh.setRect( i, x, y, w, h, r ) (method)

ID: mesh.setRect
Group: Meshes

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

  • i — int, the index of the rectangle in the mesh
  • x — float, the x coordinate used to place the rectangle
  • y — float, the y coordinate used to place the rectangle
  • w — float, the width of the rectangle
  • h — float, the height of the rectangle
  • r — float, the rotation of the rectangle

Related: mesh, mesh.addRect, mesh.setRectTex, mesh.setRectColor

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

ID: mesh.setRectTex
Group: Meshes

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

Syntax

myMesh:setRectTex( i, s, t, w, h)

Parameters

  • i — int, the index of the rectangle in the mesh
  • s — float, the left edge of the texture rectangle
  • t — float, the bottom edge of the texture rectangle
  • w — float, the width of the texture rectangle
  • h — float, the height of the texture rectangle

Related: mesh, mesh.addRect, mesh.setRect, mesh.setRectColor

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

ID: mesh.setRectColor
Group: Meshes

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

  • i — int, the index of the rectangle in the mesh
  • c — color, the color to set the rectangle to
  • r — int, the red component of the color to use
  • g — int, the green component of the color to use
  • b — int, the blue component of the color to use
  • a — int, the alpha component of the color to use

Related: mesh, mesh.addRect, mesh.setRect, mesh.setRectTex

mesh.vertex( i ) (method)

ID: mesh.vertex
Group: Meshes

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

v = myMesh:vertex( i )
myMesh:vertex( i, x, y, z )
myMesh:vertex( i, vec3 )
myMesh:vertex( i, x, y )
myMesh:vertex( i, vec2 )

Parameters

  • i — int, the index of the vertex in the mesh
  • x — float, the x position to set vertex i to
  • y — float, the y position to set vertex i to
  • z — float, the z position to set vertex i to
  • vec3 — vec3, the 3D position to set vertex i to
  • vec2 — vec2, the 2D position to set vertex i to

Returns

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

Related: mesh, mesh.texCoord, mesh.color

mesh.texCoord( i ) (method)

ID: mesh.texCoord
Group: Meshes

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

t = myMesh:texCoord( i )
myMesh:texCoord( i, x, y )
myMesh:texCoord( i, vec2 )

Parameters

  • i — int, the index of the texture coordinate in the mesh
  • x — float, the x value to set vertex i's texture coordinate to
  • y — float, the y value to set vertex i's texture coordinate to
  • vec2 — vec2, the texture coordinate value to set on vertex i

Returns

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

Related: mesh, mesh.vertex, mesh.color

mesh.color( i ) (method)

ID: mesh.color
Group: Meshes

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

c = myMesh:color( i )
myMesh:color( i, r, g, b )
myMesh:color( i, r, g, b, a )
myMesh:color( i, color )

Parameters

  • i — int, the index of the color in the mesh
  • r — int, the red value to set vertex i's color to (0 to 255)
  • g — int, the green value to set vertex i's color to (0 to 255)
  • b — int, the blue value to set vertex i's color to (0 to 255)
  • a — int, the alpha value to set vertex i's color to (0 to 255)
  • color — color, the color to set vertex i to

Returns

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

Related: mesh, mesh.vertex, mesh.texCoord, color

mesh.normal( i ) (method)

ID: mesh.normal
Group: Meshes

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

Syntax

n = myMesh:normal( i )
myMesh:normal( i, x, y, z )
myMesh:normal( i, vec3 )

Parameters

  • i — int, the index of the vertex in the mesh
  • x — float, the x magnitude of the normal for vertex i
  • y — float, the y magnitude of the normal for vertex i
  • z — float, the z magnitude of the normal for vertex i
  • vec3 — vec3, the normal to set vertex i to

Returns

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

Related: mesh, mesh.vertex, mesh.texCoord, mesh.color

mesh.resize( size ) (method)

ID: mesh.resize
Group: Meshes

This method allows you to change the size of a mesh. This will resize all of the data arrays contained in the mesh (i.e., vertices, texCoords, colors, normals). It will also resize any custom attribute buffers defined by attached shaders.

Syntax

myMesh:resize(30)

Parameters

  • size — int, the number of elements in the mesh

Related: mesh, buffer.resize, meshOverview, mesh.clear

mesh.buffer( name ) (method)

ID: mesh.buffer
Group: Meshes

This method returns the attribute buffer for particular mesh property. Buffers allow direct access to a mesh's internal data. For example, you can access the vertex positions of a mesh by calling myMesh:buffer("position"). You can then modify the returned buffer directly, and the mesh's data will be updated automatically.

If a mesh has a shader assigned to it, then you can also use the buffer method to fetch and manipulate attribute arrays that have been declared in your shader.

When you fetch a custom attribute buffer from a mesh, it is initially sized to the same size as the mesh's vertices array (i.e. the "position" buffer).

For example, if your shader has an attribute named "myAttribute" and you have assigned this shader to your mesh's shader property, then you can access the attribute array with myMesh:buffer("myAttribute") and set its data.

Syntax

b = myMesh:buffer("position")
b = myMesh:buffer("texCoord")
b = myMesh:buffer("color")
b = myMesh:buffer("normal")

Parameters

  • name — string, either "position", "texCoord", "color" or "normal" or an attribute name declared in an attached shader

Returns

A buffer object allowing direct access to an array of mesh data of a particular type

Related: mesh, buffer, shader

buffer (type)

ID: buffer
Group: Buffers

The buffer type is used in the context of a mesh to provide fast, in-place access to mesh data, such as vertices, texture coordinates, and even custom attribute arrays. Buffers simply represent an array of data with the following possible types: float, vec2, vec3, vec4, and color.

You do not create buffers directly. Instead, you access the built-in buffers on a mesh using their predefined names, or you can access attribute variables declared in your custom shader.

A mesh contains several built-in buffers (for its vertex positions, texture coordinates, colors, and normals). These can be accessed through the mesh:buffer("bufferName") method.

Syntax

b = myMesh:buffer("position")
b = myMesh:buffer("texCoord")
b = myMesh:buffer("color")
b = myMesh:buffer("normal")
b = myMesh:buffer("myAttrib")

b.instanced = true

Parameters

  • instanced — boolean, indicates whether this buffer should be treated as an instanced buffer. Defaults to false.

Returns

The newly created empty buffer

Examples

-- Accessing a built-in buffer
------------------------------
-- Create a mesh
myMesh = mesh()

-- Access its position buffer
posBuffer = myMesh:buffer("position")

-- Resize the buffer
posBuffer:resize(30)

-- Add some random vertices
for i = 1,30 do
    posBuffer[i] = vec2( math.random(-50,50),
                         math.random(-50,50) )
end

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

-- Draw the mesh
myMesh:draw()
-- Accessing a shader buffer
------------------------
-- Create a mesh
myMesh = mesh()

-- Assign a shader to myMesh
--  This shader has an attribute named 'myAttribute'
myMesh.shader = shader(asset.documents.MyShader)

-- Fetch the attribute array
myAttrBuffer = myMesh:buffer("myAttribute")

-- Resize our buffer
myAttrBuffer:resize(30)

-- Add some random numbers
for i = 1,30 do
    myAttrBuffer[i] = math.random(-50,50)
end

-- The shader will now use this data
--  when myMesh is drawn

Related: mesh, meshOverview, buffer.resize

buffer.resize( size ) (method)

ID: buffer.resize
Group: Buffers

This method allows you to change the size of a buffer. In general, you want to ensure your buffers have the same number of elements as the mesh that they belong to (i.e. the same as your mesh.size).

Buffers are initially sized to the same size as the "position" buffer in their attached mesh (i.e. mesh.vertices). Using mesh.resize will resize all mesh buffers, including your custom buffers.

Syntax

myBuffer:resize(30)

Parameters

  • size — int, the number of elements in the buffer

Related: buffer, meshOverview, mesh.buffer, mesh.resize

buffer.clear() (method)

ID: buffer.clear
Group: Buffers

This method clears all data from the buffer and sets its size to 0.

Syntax

myBuffer:clear()

Related: buffer.resize, buffer

buffer.get() (method)

ID: buffer.get
Group: Buffers

This method returns a copy of the data in buffer as a Lua table.

Syntax

myTable = myBuffer:get()

Returns

A table containing the data in buffer

Related: buffer.set, buffer

buffer.set( table ) (method)

ID: buffer.set
Group: Buffers

This method sets the content of buffer to the data contained in table.

Syntax

myBuffer:set( myTable )

Parameters

  • table — table, a table of vec2, vec3, vec4 or color

Related: buffer.get, buffer

shader (type)

ID: shader
Group: Shaders

This type represents a GLSL shader program. Shader programs are an advanced graphical tool that can be used in conjunction with mesh to provide complex graphical effects.

Shaders consist of two components, a vertex program and a fragment program. The vertex program is run on the GPU for each vertex in the mesh, and the fragment program is run for each fragment (similar to a pixel) drawn on the screen.

You can, for example, have a shader that distorts the vertices of a mesh according to a mathematical function. Or a shader that inverts the colors of a mesh's texture, and so on.

All of Codea's basic rendering effects are provided using shaders. So by supplying your own shaders, you can completely override how Codea renders elements to the screen.

In addition to loading shaders through shader packs, advanced users may also access the vertexProgram and fragmentProgram properties of shader to read and write the shader program strings directly.

Syntax

s = shader()
s = shader(asset.documents.MyShader)
s = shader(vertexProgram,
           fragmentProgram)

Parameters

  • vertexProgram — string, a string defining the vertex program of the shader
  • fragmentProgram — string, a string defining the fragment program of the shader

Returns

A newly created shader

Examples

-- Create a shader
myShader = shader(asset.documents.MyShader)

-- Assign it to a mesh
myMesh.shader = myShader

Related: shaderOverview, mesh, meshOverview, mesh.buffer

triangulate( points ) (function)

ID: triangulate
Group: Geometry Functions

Takes an array of points representing a polygon and decomposes it into a list of triangles. Points must be in clockwise or anti-clockwise order.

Syntax

triangleVertices = triangulate( points )

Parameters

  • points — table, an array of vec2 objects representing a polygon

Returns

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

music( asset ) (function)

ID: music
Group: Music

Calling this function immediately plays the music track specified by asset. The loop parameter controls whether the music track plays continuously, or stops when finished.

Only one music track can be played at a time. You can modify the currently playing music track by accessing elements of the music table, such as music.volume.

Do not call this function repeatedly in your draw loop. The music function is intended to be called once each time you wish to start playing music, or when you wish to change music tracks.

Supported music file types include: m4a, mp3, and aac

Syntax

music( asset )
music( asset, loop )
music( asset, loop, volume )
music( asset, loop, volume, pan )

Parameters

  • asset — asset key, the asset key of the music track to play
  • loop — boolean, specifies whether this track should continue playing in a loop
  • volume — number, the initial volume of playback from 0.0 to 1.0
  • pan — number, the stereo panning of playback, from -1.0 to 1.0

Examples

-- play a music track
music( asset.builtin.A_Hero_s_Quest.Battle )
-- play a looping music track
music( asset.builtin.A_Hero_s_Quest.Battle, true )
-- play a track and control the volume
-- with a parameter
music( asset.builtin.A_Hero_s_Quest.Battle, true )

parameter.number( "Volume", 0, 1, 1,
  function(val)
    music.volume = val
  end

Related: sound

music.volume (const)

ID: music.volume
Group: Music

This variable controls the currently playing music track's volume. It ranges from 0.0 to 1.0.

Syntax

-- Getting
vol = music.volume

-- Setting
music.volume = 0.5

Returns

Volume of the currently playing music track

Related: music

music.pan (const)

ID: music.pan
Group: Music

This variable controls the currently playing music track's stereo panning. It ranges from -1.0 to 1.0.

Syntax

-- Getting
pan = music.pan

-- Setting
music.pan = -1.0

Returns

Panning amount of the currently playing music track

Related: music

music.currentTime (const)

ID: music.currentTime
Group: Music

This variable controls the seek position of the currently playing music track. It ranges from 0.0 (start of the track) to music.duration (end of the track).

Syntax

-- Getting
time = music.currentTime

-- Setting
music.currentTime = music.duration * 0.5

Returns

Current time into the playing music track

Related: music.duration, music

music.paused (const)

ID: music.paused
Group: Music

This variable sets the paused state of the current music track.

Syntax

-- Getting
isPaused = music.paused

-- Setting
music.paused = true

Returns

Paused state of the currently music track.

Related: music

music.muted (const)

ID: music.muted
Group: Music

This variable controls whether the music track is currently muted.

Syntax

-- Getting
muted = music.muted

-- Setting
music.muted = true

Returns

Whether the current track is muted

Related: music

music.duration (const)

ID: music.duration
Group: Music

Read only. This variable returns the length of the current music track in seconds.

Syntax

duration = music.duration

Returns

Length of the current music track in seconds.

Related: music.currentTime, music

music.channels (const)

ID: music.channels
Group: Music

Read only. This variable returns the number of channels supported by the current track (usually 1 or 2).

Syntax

channels = music.channels

Returns

Number of channels supported by the current track.

Related: music

music.name (const)

ID: music.name
Group: Music

Read only. This value returns the asset string of the currently playing music.

Syntax

print( music.name )

Returns

Asset string of current music track

Related: music

music.stop() (function)

ID: music.stop
Group: Music

Stops the currently playing music track.

Syntax

music.stop()

Related: music

sound( name ) (function)

ID: sound
Group: Sounds

Calling this function immediately plays a sound effect, or a randomly generated sound with a type specified by name or encoded with the given parameters.

If using a sound asset (a sound from an asset pack) the sound function accepts the following optional parameters: volume, pitch, pan and loop. Please see the parameter table for an explanation of these.

sound() can use 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 parameterTable is passed in, those values are used to generate the sound.

Do not call this function repeatedly in your draw loop. The sound function is intended to be called when you wish to play a sound effect (on a game event such as the player getting hit).

Supported sound file types include: wav, caf, and aif

Syntax

-- For sound assets
sound( name, volume )
sound( name, volume, pitch )
sound( name, volume, pitch, pan )
sound( name, volume, pitch, pan, loop )

-- For generated sounds
sound( name )
sound( name, seed )
sound( parameterTable )
sound( buffer )

Parameters

  • name — asset, the sound effect asset or type of sound to play

This can be an asset name, such as asset.builtin.A_Hero_s_Quest.Arrow_Shoot_1 or it can be used to specify a randomly generated sound effect from the following: SOUND_BLIT, SOUND_EXPLODE, SOUND_HIT, SOUND_JUMP, SOUND_PICKUP, SOUND_POWERUP, SOUND_RANDOM or SOUND_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

  • volume — number, specifies the volume of the sound effect from 0.0 to 1.0 (only for sounds from an asset pack)
  • pitch — number, specifies the pitch of the sound effect, where 1.0 is the normal pitch (only for sounds from an asset pack)
  • pan — number, specifies the stereo panning of the sound effect from -1.0 to 1.0 (only for sounds from an asset pack)
  • loop — boolean, specifies whether this sound effect plays on a loop (only for sounds from an asset pack)
  • seed — int, specifies the random seed to use when generating a sound of this type
  • buffer — soundbuffer, specifies the raw sound data to play
  • parameterTable — table, specifies the parameters to use when generating a sound. This is an advanced option, the parameters will change the noise in subtle ways. Play with the Sounds Plus example app to see what these parameters do. Any missing keys will cause the sound to use a default value for that parameter

The table can contain the following (case sensitive) keys:

Waveform - The synthesizer waveform to use, can be SOUND_NOISE, SOUND_SAWTOOTH, SOUND_SINEWAVE, or SOUND_SQUAREWAVE

AttackTime - number

SustainTime - number

SustainPunch - number

DecayTime - number

StartFrequency - number

MinimumFrequency - number

Slide - number

DeltaSlide - number

VibratoDepth - number

VibratoSpeed - number

ChangeAmount - number

ChangeSpeed - number

SquareDuty - number

DutySweep - number

RepeatSpeed - number

PhaserSweep - number

LowPassFilterCutoff - number

LowPassFilterCutoffSweep - number

LowPassFilterResonance - number

HighPassFilterCutoff - number

HighPassFilterCutoffSweep - number

Volume - number

Examples

-- play some sound assets
sound( asset.builtin.A_Hero_s_Quest.Arrow_Shoot_1 )

-- At half volume
sound( asset.builtin.A_Hero_s_Quest.Arrow_Shoot_1, 0.5 )

-- Looping
sound( asset.builtin.A_Hero_s_Quest.Arrow_Shoot_1,
  1.0, 1.0, 0.0, true )
-- play a random jump sound
sound( SOUND_JUMP )

-- play a specific jump sound
sound( SOUND_JUMP, 1234 )
-- using the table to define properties
sound( { Waveform = SOUND_NOISE,
         AttackTime = 1.2,
         SustainTime = 1 } )

Related: SOUND_BLIT, SOUND_EXPLODE, SOUND_HIT, SOUND_JUMP, SOUND_PICKUP, SOUND_POWERUP, SOUND_RANDOM, SOUND_SHOOT, SOUND_NOISE, soundbuffer, SOUND_SQUAREWAVE, SOUND_SINEWAVE, SOUND_SAWTOOTH

soundbuffer( data, format, freq ) (type)

ID: soundbuffer
Group: Sounds

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

  • data — string, uncompressed audio data
  • formatFORMAT_MONO8, FORMAT_MONO16, FORMAT_STEREO8 or FORMAT_STEREO16
  • freq — integer, the frequency of the data

Returns

A new soundbuffer object

Examples

-- Creating a sound buffer object
function setup()
    tap = false
    parameter.integer("freq",1,4000,800)
    parameter.number("length",0.1,1,0.5)
end

function makeBuffer()
    local data = ""
    datum="\0\xAD\""
    numSamples = freq * length

    for i = 1,numSamples/#datum do
        data = data .. datum
    end

    return soundbuffer( 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

Related: sound

soundBufferSize( size ) (function)

ID: soundBufferSize
Group: Sounds

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

  • size — number, the maximum size of the buffer in megabytes. This can be a fraction. If this is 0, the buffer size is unlimited. An unlimited buffer size can cause Codea to crash if it runs out of memory, so take care if it is used.

Returns

If no parameters are given, a pair of values: maxBufferSize, currentBufferSize

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)

Related: sound

soundsource (type)

ID: soundsource
Group: Sounds

Created when calling the sound command, represents a live sound currently playing. Can be controlled to alter the playing sound

Syntax

source = sound(foo)

Parameters

  • volume — number, the current volume of the sound source
  • pitch — number, the current pitch of the sound source
  • pan — number, the 2D spatial location of the sound (-1 left, +1 right, 0 center)
  • looping — boolean, whether to loop the sound when it reaches the end of playback
  • paused — boolean, whether the sound source is currently paused
  • muted — boolean, whether the sound source is currently muted

Related: sound

soundsource.stop() (method)

ID: soundsource.stop
Group: Sounds

Stops the sound if it is currently playing

Syntax

soundsource.stop()

Related: soundsource

soundsource.rewind() (method)

ID: soundsource.rewind
Group: Sounds

Start the sound again from the beginning next time it is played

Syntax

soundsource.rewind()

Related: soundsource

soundsource.fadeTo() (method)

ID: soundsource.fadeTo
Group: Sounds

Fades the volume of the soundsource to the specified volume over the time specified by duration

Syntax

soundsource.fadeTo(volume, duration)

Parameters

  • volume — number, volume to fade to, between 0 and 1
  • duration — number, seconds over which to fade volume

Related: soundsource

soundsource.stopFade() (method)

ID: soundsource.stopFade
Group: Sounds

Cancels the current fading action, if possible

Syntax

soundsource.stopFade()

Related: soundsource

soundsource.pitchTo() (method)

ID: soundsource.pitchTo
Group: Sounds

Adjustes the pitch of the soundsource to the specified pitch over the time specified by duration

Syntax

soundsource.pitchTo(pitch, duration)

Parameters

  • pitch — number, pitch to fade to
  • duration — number, seconds over which to adjust pitch

Related: soundsource

soundsource.stopPitch() (method)

ID: soundsource.stopPitch
Group: Sounds

Cancels the current pitch change action, if possible

Syntax

soundsource.stopPitch()

Related: soundsource

soundsource.panTo() (method)

ID: soundsource.panTo
Group: Sounds

Adjustes the pan of the soundsource to pan over the time specified by duration

Syntax

soundsource.panTo(pan, duration)

Parameters

  • pitch — number, pan to fade to (-1 left, +1 right, 0 center)
  • duration — number, seconds over which to pan the sound

Related: soundsource

soundsource.stopPan() (method)

ID: soundsource.stopPan
Group: Sounds

Cancels the current pan change action, if possible

Syntax

soundsource.stopPan()

Related: soundsource

soundsource.stopActions() (method)

ID: soundsource.stopActions
Group: Sounds

Cancels all active actions on the soundsource, if possible

Syntax

soundsource.stopActions()

Related: soundsource

SOUND_JUMP (const)

ID: SOUND_JUMP
Group: Sounds

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

Syntax

SOUND_JUMP

Returns

The string "jump"

Related: sound

SOUND_HIT (const)

ID: SOUND_HIT
Group: Sounds

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

Syntax

SOUND_HIT

Returns

The string "hit"

Related: sound

SOUND_PICKUP (const)

ID: SOUND_PICKUP
Group: Sounds

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

Syntax

SOUND_PICKUP

Returns

The string "pickup"

Related: sound

SOUND_POWERUP (const)

ID: SOUND_POWERUP
Group: Sounds

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

Syntax

SOUND_POWERUP

Returns

The string "powerup"

Related: sound

SOUND_SHOOT (const)

ID: SOUND_SHOOT
Group: Sounds

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

Syntax

SOUND_SHOOT

Returns

The string "shoot"

Related: sound

SOUND_EXPLODE (const)

ID: SOUND_EXPLODE
Group: Sounds

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

Syntax

SOUND_EXPLODE

Returns

The string "explode"

Related: sound

SOUND_BLIT (const)

ID: SOUND_BLIT
Group: Sounds

This constant specifies a generic "blit" sound.

Syntax

SOUND_BLIT

Returns

The string "blit"

Related: sound

SOUND_RANDOM (const)

ID: SOUND_RANDOM
Group: Sounds

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

SOUND_NOISE (const)

ID: SOUND_NOISE
Group: Sounds

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

Syntax

SOUND_NOISE

Returns

The integer 3

Related: sound

SOUND_SAWTOOTH (const)

ID: SOUND_SAWTOOTH
Group: Sounds

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

Syntax

SOUND_SAWTOOTH

Returns

The integer 1

Related: sound

SOUND_SINEWAVE (const)

ID: SOUND_SINEWAVE
Group: Sounds

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

Syntax

SOUND_SINEWAVE

Returns

The integer 2

Related: sound

SOUND_SQUAREWAVE (const)

ID: SOUND_SQUAREWAVE
Group: Sounds

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

Syntax

SOUND_SQUAREWAVE

Returns

The integer 0

Related: sound

speech (type)

ID: speech
Group: Speech

This type represents a spoken utterance that can be played back using the speech.say() function. It consists of a string and other properties which determine the volume, speed and pitch of playback.

Multiple utterances can be queued for playback with the speech.say() function. The utterances will be separated by their respective preDelay and postDelay intervals.

Note that speech can be used to construct utterances to be used later, but it can also be used as a global table that can be configured for all future speech. See the two examples for both kinds of use.

Syntax

speech( string )
speech.pitch
speech.volume
speech.rate
speech.preDelay
speech.postDelay

Parameters

  • string — string, the utterance to be spoken
  • pitch — float, a value between 0.5 and 2.0, raises or lowers the pitch (default is 1.0)
  • rate — float, a value between 0.0 and 1.0, the speed at which the utterance is spoken (default is 0.1)
  • preDelay — float, the amount of time to wait before speaking this utterance
  • postDelay — float, the amount of time to wait after speaking this utterance
  • volume — float, a value between 0.0 and 1.0 (default is 1.0)
  • voices — table, an array of available voice objects
  • voice — voice, the default voice to use for speech, use nil for default
  • language — string, the language string representing the voice you wish to use

Returns

The newly created utterance to be used with speech.say

Examples

-- This example uses global speech
-- functions and settings

-- Set speech volume for next
-- use of speech.say()
speech.volume = 0.7

-- Queue up a sentence
speech.say("Hello World")

-- Raise the pitch
speech.pitch = 1.5

-- Queue up another sentence
speech.say("I'm Talking")
-- This example creates actual
-- utterance objects

-- Create an utterance to use
local words = speech("Hello World")
local moreWords = speech("I'm Talking")

words.volume = 0.7

moreWords.pitch = 1.5

-- Queue up two utterances
speech.say( words )
speech.say( moreWords )
-- An example of voices

-- List all voices
for _,v in pairs(speech.voices) do
    print(v)
end

-- Set default language
speech.language = "en-GB"

-- Set specific voice
-- (Overrides language setting)
speech.voice = speech.voices[1]

Related: speech.say, speech.pause, speech.continue, speech.stop

speech.say( string ) (function)

ID: speech.say
Group: Speech

This function can be used to speak a particular string or utterance. Calling this function multiple times will add more utterances to the queue to be spoken, it will not stop anything currently being spoken. Use speech.stop or speech.pause to control playback.

Syntax

speech.say( string )
speech.say( utterance )

Parameters

  • string — string, a string to speak

Examples

-- Adjust the speech settings
speech.volume = 0.6

-- Just speak some words immediately
--  will be spoken at 0.6 volume
speech.say("Hello world!")

-- Adjust settings for next words
speech.volume = 1.0
speech.pitch = 1.5

-- Queue up another sentence to speak
-- after the above is finished
--  will be spoken louder, in high pitch
speech.say("I'm talking")

Related: speech, speech.pause, speech.continue, speech.stop, speech.speaking

speech.pause() (function)

ID: speech.pause
Group: Speech

This function can be used to pause anything currently being spoken. Speech will pause after the next word by default. Pass a value of true to this function to pause speech immediately.

After speech is paused, it can be continued with the speech.continue() function.

Syntax

speech.pause()
speech.pause( immediate )

Parameters

  • immediate — boolean, whether to pause immediately or after the next word

Examples

-- Just speak some words immediately
speech.say("Hello world!")

-- Pause it
speech.pause()

-- Later, continue
speech.continue()

Related: speech.continue, speech.stop, speech.say

speech.stop() (function)

ID: speech.stop
Group: Speech

This function can be used to stop anything currently being spoken. Speech will stop after the next word by default. Pass a value of true to this function to stop speech immediately.

Unlike speech.pause speech which has been stopped cannot be resumed with the speech.continue() function.

Syntax

speech.stop()
speech.stop( immediate )

Parameters

  • immediate — boolean, whether to stop immediately or after the next word

Examples

-- Just speak some words immediately
speech.say("Hello world!")

-- Stop it immediately
speech.stop( true )

Related: speech.continue, speech.pause, speech.say

speech.continue() (function)

ID: speech.continue
Group: Speech

Use this function to resume speech which has been paused with speech.pause

Syntax

speech.continue()

Related: speech.pause, speech.say

speech.speaking (const)

ID: speech.speaking
Group: Speech

Check this value to see if the speech synthesizer is currently speaking.

Syntax

speech.speaking

Returns

Boolean value indicating whether the system is currently speaking

Related: speech.say

speech.paused (const)

ID: speech.paused
Group: Speech

Check this value to see if the speech synthesizer is currently paused.

Syntax

speech.paused

Returns

Boolean value indicating whether the system is currently paused

Related: speech.say

speech.pitch (const)

ID: speech.pitch
Group: Speech

Set this value to control the pitch of speech playback with speech.say. This value ranges from 0.5 to 2.0, the default is 1.0.

Syntax

speech.pitch = 2.0

Returns

float value, the current global speech pitch

Related: speech

speech.rate (const)

ID: speech.rate
Group: Speech

Set this value to control the rate (speed) of speech playback with speech.say. This value ranges from 0.0 to 1.0, the default is 0.5.

Syntax

speech.rate = 0.1

Returns

float value, the current global speech rate

Related: speech

speech.preDelay (const)

ID: speech.preDelay
Group: Speech

Set this value to control the pre delay of speech played back with speech.say. Speech will be delayed by this amount prior to playback. Defaults to 0.0.

Syntax

speech.preDelay = 0.0

Returns

float value, the delay in seconds prior to playing speech

Related: speech

speech.postDelay (const)

ID: speech.postDelay
Group: Speech

Set this value to control the post delay of speech played back with speech.say. A pause for this amount of time will occur after speech played back and before the next queued speech.

Syntax

speech.postDelay = 0.0

Returns

float value, the delay in seconds after playing speech

Related: speech

speech.volume (const)

ID: speech.volume
Group: Speech

Set this value to control volume of speech played back with speech.say. This value can range between 0.0 and 1.0. It defaults to 1.0.

Syntax

speech.volume = 1.0

Returns

float value, the volume of speech

Related: speech

mic.start() (function)

ID: mic.start
Group: Microphone

Use this function to start tracking input from the device microphone

Syntax

mic.start()

Related: mic.stop

mic.stop() (function)

ID: mic.stop
Group: Microphone

Use this function to stop tracking input from the device microphone

Syntax

mic.stop()

Related: mic.start

mic.amplitude (const)

ID: mic.amplitude
Group: Microphone

Sample this value to determine the volume of sound coming into the microphone

Syntax

local amp = mic.amplitude

Related: mic.frequency

mic.frequency (const)

ID: mic.frequency
Group: Microphone

Sample this value to determine the pitch of sound coming into the microphone

Syntax

local freq = mic.frequency

Related: mic.amplitude

pasteboard.copy( text ) (function)

ID: pasteboard.copy
Group: Pasteboard

This function copies either image or text data to the system pasteboard. It can then be pasted elsewhere or read back into Codea using the pasteboard.text and pasteboard.image values.

Syntax

pasteboard.copy( text )
pasteboard.copy( image )

Parameters

  • text — string, text to be copied to the pasteboard
  • image — image, image data to be copied to the pasteboard, such as image data returned by readImage or the image() function

Examples

-- Copy some text to the pasteboard
pasteboard.copy( "Some text" )

-- Read the text back out
print( pasteboard.text )

Related: pasteboard.text, pasteboard.image

pasteboard.text (const)

ID: pasteboard.text
Group: Pasteboard

This value specifies any text that has been copied to the system pasteboard. It is nil if there is no text data on the pasteboard.

You may also assign text to this value, which is identical to calling pasteboard.copy( text ).

Syntax

text = pasteboard.text

Returns

Text currently on the system pasteboard, nil if there is none.

Examples

-- Check if we have text
if pasteboard.text then
    -- Print text
    print( pasteboard.text )
end
-- Copy some text to the pasteboard
pasteboard.text = "Hello Pasteboard"

Related: pasteboard.copy, pasteboard.image

pasteboard.image (const)

ID: pasteboard.image
Group: Pasteboard

This value specifies an image that has been copied to the system pasteboard. It is nil if there is no image data on the pasteboard.

You may also assign an image to this value, which is identical to calling pasteboard.copy( image ).

Syntax

img = pasteboard.image

Returns

Image currently on the system pasteboard, nil if there is none.

Examples

-- Check if we have an image
if pasteboard.image then
    -- Render image
    sprite( pasteboard.image, WIDTH/2, HEIGHT/2 )
end
-- Copy an image to the pasteboard
local img = image(100,100)
pasteboard.image = img

Related: pasteboard.copy, pasteboard.text

readImage( asset ) (function)

ID: readImage
Group: Saving and Reading Assets

This function reads a stored image into an image type. You can read from the included asset locations, or from any accessible location in your file system (project, documents, etc).

The width and height parameters are only used for vector sprites. These tell Codea what resolution to rasterize the sprite at. If they are not specified, then the sprite is rendered at the size specified in the vector source file. If only the width is specified, the height is computed based on the aspect ratio.

Syntax

readImage( asset )
readImage( asset, width )
readImage( asset, width, height )
readImage( asset, width, height, page )

Parameters

  • asset — asset, asset key to image file (e.g., asset.documents.MySprite)
  • width — int, for vector sprites only. The desired width at which the vector sprite is to be rendered.
  • height — int, for vector sprites only. The desired height at which the vector sprite is to be rendered.
  • page — int, for multi-page vector sprites only. Selects the page (starting at 1) of the vector sprite to render as an image. To get the number of pages, use spriteSize.

Returns

The image associated with asset or nil if asset doesn't exist or is invalid.

Examples

-- Read a sprite into an image
myImage = readImage(asset.builtin.Planet_Cute.Heart)

Related: saveImage, image, assetList, assetsOverview

saveImage( asset, image ) (function)

ID: saveImage
Group: Saving and Reading Assets

This function saves an image into storage. Only user writeable locations (such as asset or asset.documents) are permitted for this operation. If an existing sprite exists under the asset key it will be overwritten, if nil is specified for the image parameter then the sprite at the asset key 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.

Syntax

saveImage( asset, image )

Parameters

  • asset — asset, asset key for the file to save (e.g., asset .. "MyFile.png" )
  • image — image, the image to be saved under asset

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

    -- We create a path to file "Circle.png"
    -- by using the .. operator
    saveImage(asset.documents .. "Circle.png", myImage)
end

Related: readImage, image, assetList

readText( asset ) (function)

ID: readText
Group: Saving and Reading Assets

This function reads a stored plain text file into a string. You can read from the included asset locations, or your Documents, Project or elsewhere.

Syntax

readText( asset )

Parameters

  • asset — asset, asset key to text file (e.g., asset.documents.Readme)

Returns

The text content of asset or nil if asset does not exist or is invalid.

Examples

-- Read a text file into a string
myString = readText(asset.documents.MyFile)

Related: saveText

saveText( asset, text ) (function)

ID: saveText
Group: Saving and Reading Assets

This function saves text to the location at asset. Only user writeable locations (such as asset or asset.documents) are permitted for this operation. If an existing asset exists at the path specified by asset it will be overwritten, if nil is specified for the text parameter then the file at asset will be deleted.

Syntax

saveText( asset, text )

Parameters

  • asset — asset, asset key for the file to save (e.g., asset .. "MyFile.txt" )
  • text — string, the text contents to be saved under asset

Examples

-- Save some text content into documents
function setup()
    myContent = "Hello World"

    saveText(asset.documents .. "Hello.txt", myContent)
end

Related: readText

file.copy( source, destination ) (function)

ID: file.copy
Group: File Operations

This function copies a file or folder from one location to another. Returns success status and error message. When copying to an asset library (folder), the file maintains its original name in the destination. Fails if the source does not exist or if the destination already exists.

Syntax

file.copy( source, destination )

Parameters

  • source — asset key or asset library, source file or folder to copy
  • destination — asset key or asset library, destination path or folder

Returns

Two values: success (boolean) and error message (string or nil). On success: true, nil. On failure: false, "error message".

Examples

-- Copy a file to documents with a new name
local ok, err = file.copy(asset.builtin.Pack.File, asset.documents .. "MyFile.png")
if not ok then
    print("Copy failed:", err)
end

-- Copy a file to documents (keeps original name)
local ok, err = file.copy(asset.builtin.Pack.File, asset.documents)

-- Copy an entire folder
local ok, err = file.copy(asset.builtin.Pack, asset.documents .. "MyPack")

Related: file.move, file.remove, file.rename, file.mkdir

file.move( source, destination ) (function)

ID: file.move
Group: File Operations

This function moves a file or folder from one location to another. Returns success status and error message. When moving to an asset library (folder), the file maintains its original name in the destination. Fails if the source does not exist or if the destination already exists.

Syntax

file.move( source, destination )

Parameters

  • source — asset key or asset library, source file or folder to move
  • destination — asset key or asset library, destination path or folder

Returns

Two values: success (boolean) and error message (string or nil). On success: true, nil. On failure: false, "error message".

Examples

-- Move a file to documents with a new name
local ok, err = file.move(asset.icloud.Pack.File, asset.documents .. "MyFile.png")
if not ok then
    print("Move failed:", err)
end

-- Move a file to documents (keeps original name)
local ok, err = file.move(asset.icloud.Pack.File, asset.documents)

-- Move an entire folder
local ok, err = file.move(asset.icloud.Pack, asset.documents .. "MyPack")

Related: file.copy, file.remove, file.rename, file.mkdir

file.remove( asset ) (function)

ID: file.remove
Group: File Operations

This function removes a file or folder. Returns success status and error message. Built-in folders and top-level asset packs (asset, asset.builtin, asset.documents, asset.icloud) cannot be removed. Fails if the file does not exist.

Syntax

file.remove( asset )

Parameters

  • asset — asset key or asset library, file or folder to remove

Returns

Two values: success (boolean) and error message (string or nil). On success: true, nil. On failure: false, "error message".

Examples

-- Remove a file
local ok, err = file.remove(asset.documents.File)
if not ok then
    print("Remove failed:", err)
end

-- Remove a folder and all its contents
local ok, err = file.remove(asset.documents.SomeFolder)

Related: file.copy, file.move, file.rename, file.mkdir

file.mkdir( asset ) (function)

ID: file.mkdir
Group: File Operations

This function creates a new directory. Returns success status and error message. Fails if the directory already exists or if the parent directory does not exist.

Syntax

file.mkdir( asset )

Parameters

  • asset — asset key or asset library, path where the directory should be created

Returns

Two values: success (boolean) and error message (string or nil). On success: true, nil. On failure: false, "error message".

Examples

-- Create a new folder in documents
local ok, err = file.mkdir(asset.documents .. "MyFolder")
if not ok then
    print("Create directory failed:", err)
end

-- Will fail if parent doesn't exist
local ok, err = file.mkdir(asset.documents .. "Parent/Child")
-- First create parent, then child
file.mkdir(asset.documents .. "Parent")
file.mkdir(asset.documents .. "Parent/Child")

Related: file.copy, file.move, file.remove, file.rename

file.rename( asset, newName ) (function)

ID: file.rename
Group: File Operations

This function renames a file or folder within the same parent directory. Returns success status and error message. This is a synonym for moving within the same parent folder to a new name. Fails if the source does not exist or a sibling with the new name already exists.

Syntax

file.rename( asset, newName )

Parameters

  • asset — asset key, source file or folder to rename
  • newName — string, the new name for the file or folder

Returns

Two values: success (boolean) and error message (string or nil). On success: true, nil. On failure: false, "error message".

Examples

-- Rename a file within documents
local ok, err = file.rename(asset.documents .. "Old.png", "New.png")
if not ok then
    print("Rename failed:", err)
end

-- Rename a folder within documents
local ok, err = file.rename(asset.documents .. "OldFolder", "NewFolder")

Related: file.copy, file.move, file.remove, file.mkdir

file.exists( asset ) (function)

ID: file.exists
Group: File Operations

This function checks if a file or folder exists at the given path. Returns a boolean value.

Syntax

file.exists( asset )

Parameters

  • asset — asset key or asset library, path to check for existence

Returns

boolean, true if the path exists, false otherwise

Examples

-- Check if a configuration file exists
if file.exists(asset.documents .. "Config.json") then
    print("Config is present")
else
    print("Missing Config.json")
end

-- Check if a folder exists
if file.exists(asset.documents .. "Screenshots") then
    print("Screenshots folder exists")
end

Related: file.copy, file.move, file.remove, file.mkdir, file.rename

json.encode( object ) (function)

ID: json.encode
Group: JSON

This function encodes an object into a JSON string. object can be a table, string, number, boolean, nil, or any object implementing the __tojson metamethod.

A state table can be optionally provided to configure the output string.

Syntax

json.encode( object )
json.encode( object, state )

Parameters

  • object — table or other object to encode into JSON string
  • state — optional table with the following keys

indent - boolean specifying whether returned string will contain newlines and indentations keyorder - array specifying ordering of keys in the encoded output, unspecified keys will be written after ordered keys level - number of spaces to indent per level buffer - an array to store the strings for the result (in which case the resulting JSON string will not be returned, instead it will be buffer) bufferlen - index of the last element of buffer exception - a function to be called when the encoder cannot encode a given value. Will be given the parameters, reason, value, state, and defaultmessage.

Returns

string value for object encoded as JSON string (or a boolean indicating success if a custom buffer was specified)

Examples

-- Generate a JSON string
local t = {hello="world"}
local str = json.encode(t)

-- Save into current project
saveText(asset .. "data.json", str)

Related: json.decode

json.decode( string ) (function)

ID: json.decode
Group: JSON

This function decodes a JSON encoded string into an object (usually a table).

Syntax

json.decode( string )
json.decode( string, position )
json.decode( string, position, null )

Parameters

  • string — string to decode
  • position — integer, optional and specifies the starting index wihtin the string to decode
  • optional value to be returned for null values within the JSON string, defaults to nil

Returns

an object represented by the decoded string JSON string

Examples

-- Read a text asset and decode it
-- into a table
local myData = readText(asset.data)
local t = json.decode(myData)

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

Related: json.encode

readLocalData( key ) (function)

ID: readLocalData
Group: Local Storage

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

  • key — string, name of the piece of data you would like to get
  • defaultValue — if the key doesn't exist, this value is returned instead

Returns

The value associated with key, or defaultValue if key doesn't exist and defaultValue is specified. nil if key doesn't exist and defaultValue is not specified.

Examples

-- Load high score
-- Defaults to 0 if it doesnt exist
highscore = readLocalData("highscore", 0)

Related: saveLocalData, clearLocalData

saveLocalData( key, value ) (function)

ID: saveLocalData
Group: Local Storage

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

  • key — string, name of the piece of data you would like to store
  • value — the value to store under key

Examples

-- Save high score
saveLocalData("highscore", currentScore)

Related: readLocalData, clearLocalData

listLocalData() (function)

ID: listLocalData
Group: Local Storage

This function returns a table containing all the keys in local storage.

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

listLocalData( )

Returns

A table containing all the keys stored in local data

Related: readLocalData, saveLocalData, clearLocalData

clearLocalData() (function)

ID: clearLocalData
Group: Local Storage

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: readLocalData, saveLocalData

readProjectData( key ) (function)

ID: readProjectData
Group: Project Storage

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

  • key — string, name of the piece of data you would like to get
  • defaultValue — if the key doesn't exist, this value is returned instead

Returns

The value associated with key, or defaultValue if key doesn't exist and defaultValue is specified. nil if key doesn't exist and defaultValue is not specified.

Related: saveProjectData, clearProjectData

saveProjectData( key, value ) (function)

ID: saveProjectData
Group: Project Storage

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

  • key — string, name of the piece of data you would like to store
  • value — the value to store under key

Related: readProjectData, clearProjectData

saveProjectInfo( key, value ) (function)

ID: saveProjectInfo
Group: Project Storage

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

  • key — string, name of the project metadata to store. Currently supports "Description" and "Author"
  • value — the value to store under key

Related: readProjectInfo

readProjectInfo( key ) (function)

ID: readProjectInfo
Group: Project Storage

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

Syntax

readProjectInfo( key )

Parameters

  • key — string, name of the piece of metadata you would like to get

Returns

The value associated with key, or nil if the key does not exist

Related: saveProjectInfo

listProjectData() (function)

ID: listProjectData
Group: Project Storage

This function returns a table containing all the keys stored in project 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

listProjectData( )

Returns

A table containing all the keys stored in project data

Related: readProjectData, saveProjectData, clearProjectData

clearProjectData() (function)

ID: clearProjectData
Group: Project Storage

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: readProjectData, saveProjectData

readGlobalData( key ) (function)

ID: readGlobalData
Group: Global Storage

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

  • key — string, name of the piece of data you would like to get
  • defaultValue — if the key doesn't exist, this value is returned instead

Returns

The value associated with key, or defaultValue if key doesn't exist and defaultValue is specified. nil if key doesn't exist and defaultValue is not specified.

Related: saveGlobalData, clearProjectData

saveGlobalData( key, value ) (function)

ID: saveGlobalData
Group: Global Storage

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

  • key — string, name of the piece of data you would like to store
  • value — the value to store under key

Related: readGlobalData

listGlobalData() (function)

ID: listGlobalData
Group: Global Storage

This function returns a table containing all the keys stored in global data.

Global storage is shared among all projects on this device.

Syntax

listGlobalData( )

Returns

A table containing all the keys stored in global data

Related: readGlobalData, saveGlobalData

readProjectTab( key ) (function)

ID: readProjectTab
Group: Projects and Tabs

This function can be used to read the contents of a tab in the current project, or in another project. The contents of the tab are returned as a string. The key parameter specifies the tab to read, and can optionally include the project name to read from. If no project name is specified, the tab is read from the current project.

The key parameter takes the form "Project Name:Tab Name". "Project Name" specifies the project to read from, and "Tab Name" specifies the tab to read. If "Project Name" is not specified, "Tab Name" is assumed to exist in the currently running project, and is read from there.

If the key can not be found, then an error is printed and playback is paused.

Syntax

readProjectTab( key )

Parameters

  • key — string, a key specifying the project and tab you would like to read

Returns

A string containing the contents of the tab specified by key. If key is not found, returns nothing.

Examples

-- Read the main tab in the current project
mainTab = readProjectTab("Main")

-- Print the results
print( mainTab )
-- Read the main tab in a different project
mainTab = readProjectTab("My Project:Main")

-- Print the results
print( mainTab )

Related: saveProjectTab, listProjectTabs

saveProjectTab( key, value ) (function)

ID: saveProjectTab
Group: Projects and Tabs

This function can be used to save the contents of a tab in the current project, or in another user project.

The key parameter takes the form "Project Name:Tab Name". "Project Name" specifies the project to save to, and "Tab Name" specifies the tab to write. If "Project Name" is not specified, "Tab Name" is assumed to exist in the currently running project.

The value parameter is a string that is written to the location specified by key. If value is nil, then Codea will delete the tab specified by key.

Syntax

saveProjectTab( key, value )

Parameters

  • key — string, a key specifying a project and tab
  • value — string, the contents to write into the tab specified by key, a value of nil deletes the tab.

Examples

-- Create a tab named "Test"
-- In the current project
saveProjectTab("Test", "-- This is a test!")
-- Delete the tab named "Test"
-- In the current project
saveProjectTab("Test", nil)

Related: readProjectTab, listProjectTabs

listProjectTabs() (function)

ID: listProjectTabs
Group: Projects and Tabs

This function returns a table containing all the tabs in the specified project.

If no argument is provided, this function will return a table containing all the tabs in the currently running project. If a value is specified for project then the tab list will be fetched from that project.

Syntax

listProjectTabs( )
listProjectTabs( project )

Parameters

  • project — string, the name of a project to retrieve tabs from

Returns

A table containing all the tabs in the specified project

Related: readProjectTab, saveProjectTab

createProject( key ) (function)

ID: createProject
Group: Projects and Tabs

This function will create a new project with the specified name. The key parameter specifies a project name (e.g., "Project Name"), or a collection and project name in the form "Collection Name:Project Name".

If the specified project name already exists then this function will report an error and playback will pause.

The default collection for project storage is reserved under the name "documents".

Syntax

createProject( key )

Parameters

  • key — string, a key specifying the project you would like to create

Examples

-- Create a new project in the default location
createProject("My Project")
-- Create a new project in the examples collection
createProject("Examples:My Project")

Related: hasProject, deleteProject, listProjects

deleteProject( key ) (function)

ID: deleteProject
Group: Projects and Tabs

This function will delete the specified project. The key parameter specifies a project name ("Project Name"), or a collection and project name in the form "Collection Name:Project Name".

If the specified project does not exist then this function will report an error and playback will pause. If the specified project is the currently running project then this function will report an error and playback will pause.

The default collection for project storage is reserved under the name "documents".

Syntax

deleteProject( key )

Parameters

  • key — string, a key specifying the project you would like to delete

Examples

-- Delete a project
deleteProject("Examples:Anagrams")

Related: createProject, hasProject, listProjects

hasProject( key ) (function)

ID: hasProject
Group: Projects and Tabs

This function will return true if the specified project exists. The key parameter specifies a project name ("Project Name"), or a collection and project name in the form "Collection Name:Project Name".

If the specified project does not exist then this function will return false.

The default collection for project storage is reserved under the name "documents".

Syntax

hasProject( key )

Parameters

  • key — string, a key specifying the project you would like to query

Returns

true if the specified project exists, false otherwise

Examples

-- Check if an example exists
print(hasProject("Examples:Anagrams"))

Related: createProject, deleteProject, listProjects

listProjects() (function)

ID: listProjects
Group: Projects and Tabs

If no arguments are provided, this function returns a table containing all the projects on your device. If the collection is specified (e.g., "Examples") then only projects from that collection are returned.

If a collection is specified, then the returned project names will be unqualified. That is, they will not be prefixed with the collection name. If no collection is specified, then the returned projects will be fully qualified with the collection name (except for those projects which reside in the default "documents" collection).

The default collection for project storage is reserved under the name "documents".

Syntax

listProjects( )
listProjects( collection )

Parameters

  • collection — string, the name of the collection to retrieve projects from

Returns

A table containing all the projects in the specified collection, or all projects in all collections if none specified

Related: createProject, hasProject, deleteProject

CurrentTouch (const)

ID: CurrentTouch
Group: Handling Touches

This global variable always represents the first available touch on the screen. It is a touch datatype, see the related items for more information.

Syntax

CurrentTouch

Examples

function draw()
    background( 0 )
    fill( 255, 0, 0 )
    ellipse( CurrentTouch.x, CurrentTouch.y, 300 )
end

Related: touch

touch (type)

ID: touch
Group: Handling Touches

This type represents data about a single touch on the screen

Syntax

touch.id
touch.pos
touch.prevPos
touch.precisePos
touch.precisePrevPos
touch.delta
touch.force
touch.maxForce
touch.altitude
touch.azimuth
touch.azimuthVec
touch.type
touch.state
touch.tapCount
touch.timestamp

Parameters

  • id — int, a unique identifier for this touch
  • pos — vec2, specifies the position of the touch on the screen
  • prevPos — vec2, specifies the position, from the previous frame, of the touch on the screen
  • precisePos — vec2, specifies the precise position of the touch on the screen (when available, for example, when using a stylus)
  • precisePrevPos — vec2, specifies the precise position, from the previous frame, of the touch on the screen (when available, for example, when using a stylus)
  • delta — vec2, specifies the delta since the last frame, the amount the touch has moved
  • force — float, when available, specifies the force of the touch
  • maxForce — float, when available, specifies the maximum possible force of a touch
  • altitude — float, stylus only, angle in radians of the stylus with the surface of the screen. A value of 0 indicates the stylus is parallel to the screen, a value of Pi/2 indicates a stylus perpendicular to the screen
  • azimuth — float, stylus only, angle in radians of the direction in which the stylus is pointing
  • azimuthVec — vec2, stylus only, a unit vector which points in the direction of the stylus
  • type — the type of the touch, can be DIRECT, INDIRECT, STYLUS or POINTER
  • state — the state of the touch, can be BEGAN, CHANGED, ENDED or CANCELLED
  • tapCount — how many times the touch has been tapped
  • timestamp — the time when the touch occurred or when it was last updated

Related: touched, CurrentTouch

function touched(touch) (event)

ID: touched
Group: Handling Touches

Codea calls this function, if it is defined in your project, whenever a finger touches the screen in the viewing area. The touched function is passed a touch object containing information about the touch, such as position, type, state, and so on.

If the user touches the screen with multiple fingers this function is called repeatedly for each active touch. touch objects have an id (touch.id) to allow you to store, track and differentiate them over repeated calls to this function. A touch will maintain its id through its life time (from state BEGAN through to state ENDED or CANCELLED)

You can use the type of the touch to determine whether it comes from a finger (DIRECT), stylus (STYLUS) or a trackpad or mouse (POINTER)

Syntax

function touched(touch)

Parameters

  • gesture — the gesture object containing information about this event

Related: touch, CurrentTouch

gesture (type)

ID: gesture
Group: Gestures

Gestures are used to represent interaction from a pointer or trackpad, such as hovering or scrolling in the viewer.

Codea supports two types of gestures for the viewer, hover and scroll.

Hover gestures occur when moving a pointer over the viewer. When this happens Codea calls the global function hover(gesture) and passes a gesture object containing information about the hover event. The gesture contains a state and location. Location is a vec2 indicating where the pointer is hovering over the viewer. The state can be BEGAN, CHANGED, or ENDED

Scroll gestures occur when two-finger scrolling is detected on a trackpad. Codea calls the global function scroll(gesture) and passes a gesture object containing information about the scroll event. The gesture contains state, location, translation, and delta. State and location are similar to hover (above). translation is a vec2 reflecting the total amount of 2D translation that has occurred since the scrolling began. delta is a vec2 of the amount of 2D translation since the last time scroll was called

Pinch gestures occur when two-finger pinching is detected on a trackpad. Codea calls the global function pinch(gesture) and passes a gesture object containing information about the pinch event. The gesture contains state, location, pinchScale, and pinchVelocity. State and location are similar to hover and scoll (above). pinchScale is a number reflecting the total amount of scale that has occurred since the pinch began. pinchVelocity is a number of the velocity of of the pinch scale in scale factor per second

Gestures also include information on which modifier keys have been pressed during the event, such as gesture.shift and gesture.command. If these values are true it indicates that modifier key was held down

Syntax

gesture.state
gesture.location
gesture.translation
gesture.delta
gesture.pinchScale
gesture.pinchVelocity
gesture.alt
gesture.control
gesture.command
gesture.shift
gesture.capsLock

Parameters

  • state — the state of the gesture, can be BEGAN, CHANGED or ENDED
  • location — vec2, the location of the gesture over the viewer
  • translation — vec2, scroll gestures only. The total amount of 2D translation since the gesture began
  • delta — vec2, scroll gestures only. The amount of 2D translation since the last time scroll was called
  • pinchScale — number, pinch gestures only. The scale of the pinch relative to the two touches since the gesture began
  • pinchVelocity — number, pinch gestures only. The velocity of the change in pinch scale in scale factor per second
  • alt — bool, true if the alt (alternate / option) modifier key was held down
  • control — bool, true if the control modifier key was held down
  • command — bool, true if the command modifier key was held down
  • shift — bool, true if the shift modifier key was held down
  • capsLock — bool, true if the caps lock key was held down

Related: hover, scroll, pinch, vec2, BEGAN, CHANGED, ENDED

function hover(gesture) (event)

ID: hover
Group: Gestures

Codea calls this function, if it is defined in your project, whenever a pointer hovers in the viewer. Hovering occurs when a connected mouse or trackpad pointer moves over the screen without clicking. The hover function is passed a gesture parameter which contains the x,y location of the event as a vec2

The gesture parameter of this function also has a state field, which can tell you if the event has BEGAN, or CHANGED since the last call, or ENDED. The hover function will be called continuously as the pointer moves across the screen with updated x,y coordinates until it eventually ends due to the pointer moving out of the viewer area, or the pointer fading if the input device is not touched

Syntax

function hover(gesture)

Parameters

  • gesture — the gesture object containing information about this event

Related: gesture, scroll, pinch, vec2

function scroll(gesture) (event)

ID: scroll
Group: Gestures

Codea calls this function, if it is defined in your project, whenever a scroll event occurs in the viewer. This is usually triggered by a two-finger drag on an attached trackpad input device

The gesture parameter of this function contains information about the scroll event. Including its location, translation and delta. Translation (vec2) is the 2D magnitude of the scroll since the scroll began (gesture.state == BEGAN). Delta (vec2) is the 2D magnitude of the scroll since the last scroll update. The delta can be accumulated to track a scroll over time, or the translation can be applied to a fixed starting point to compute the desired end point — the starting point can be updated at the ENDED state of the scroll event

Syntax

function scroll(gesture)

Parameters

  • gesture — the gesture object containing information about this event

Related: gesture, hover, pinch, vec2

function pinch(gesture) (event)

ID: pinch
Group: Gestures

Codea calls this function, if it is defined in your project, whenever a pinch event occurs in the viewer. This is triggered by a two-finger pinch on an attached trackpad input device

The gesture parameter of this function contains information about the pinch event. Including its location, pinchScale and pinchVelocity. pinchScale (float) is the magnitude of the pinch since the pinch began (gesture.state == BEGAN). pinchVelocity (float) is the velocity of the pinch in scale factor per second. The velocity can be accumulated to perform a scale over time, centered around location

Syntax

function pinch(gesture)

Parameters

  • gesture — the gesture object containing information about this event

Related: gesture, hover, scroll, vec2

BEGAN (const)

ID: BEGAN
Group: Touch States

This state occurs when a touch or gesture first begins

Syntax

BEGAN

Related: touch

CHANGED (const)

ID: CHANGED
Group: Touch States

This state occurs when a touch or gesture changes position

Syntax

CHANGED

Related: touch

ENDED (const)

ID: ENDED
Group: Touch States

This state occurs when a touch or gesture ends (e.g., by the user lifting their finger from the screen)

Syntax

ENDED

Related: touch

CANCELLED (const)

ID: CANCELLED
Group: Touch States

This state occurs when the system interrupts the touch for some reason (e.g., system alert, notification window slid down, multitasking entered). This state can generally be handled similarly to ENDED.

Syntax

CANCELLED

Related: touch, ENDED

DIRECT (const)

ID: DIRECT
Group: Touch Types

Direct touches occur when the user's finger touches the screen

Syntax

DIRECT

Related: touch

INDIRECT (const)

ID: INDIRECT
Group: Touch Types

Indirect touches are generated by touch input devices that are separate from the screen. For example, a remote pointing device

Syntax

INDIRECT

Related: touch

STYLUS (const)

ID: STYLUS
Group: Touch Types

A stylus touch occurs when a stylus interacts with the device's screen

Syntax

STYLUS

Related: touch

POINTER (const)

ID: POINTER
Group: Touch Types

A pointer touch occurs when using an indirect input device such as a trackpad or mouse

Syntax

POINTER

Related: touch

vec2 (type)

ID: vec2
Group: 2D Vector

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

  • x — number, the x component of this vec2
  • y — number, the y component of this 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))

Related: vec2.dot, vec2.normalize, vec2.dist, vec2.distSqr, vec2.len, vec2.lenSqr, vec2.cross, vec2.rotate, vec2.rotate90, vec2.angleBetween

vec2.dot( vector ) (method)

ID: vec2.dot
Group: 2D Vector

This method returns the scalar dot product between two vec2 types

Syntax

v1 = vec2( 1, 1 )
x = v1:dot( v )

Parameters

  • vector — vec2, compute the dot product with this vector

Returns

number, dot product between this vec2 and vector

Related: vec2

vec2.normalize() (method)

ID: vec2.normalize
Group: 2D Vector

This method returns a normalized version of the vector

Syntax

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

Returns

vec2, normalized version of this vec2

Related: vec2

vec2.dist( v ) (method)

ID: vec2.dist
Group: 2D Vector

This method returns the distance between two vec2 types

Syntax

v1 = vec2( 1, 1 )
x = v1:dist( vec2(2, 2) )

Parameters

  • vector — vec2, compute the distance to this vector

Returns

number, distance between this vec2 and vector

Related: vec2

vec2.distSqr( v ) (method)

ID: vec2.distSqr
Group: 2D Vector

This method returns the squared distance between two vec2 types

Syntax

v1 = vec2( 1, 1 )
x = v1:distSqr( vec2(2, 2) )

Parameters

  • vector — vec2, compute the squared distance to this vector

Returns

number, squared distance between this vec2 and vector

Related: vec2

vec2.len() (method)

ID: vec2.len
Group: 2D Vector

This method returns the length of a vec2

Syntax

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

Returns

number, length of this vec2

Related: vec2

vec2.lenSqr() (method)

ID: vec2.lenSqr
Group: 2D Vector

This method returns the squared length of a vec2

Syntax

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

Returns

number, squared length of this vec2

Related: vec2

vec2.cross( vector ) (method)

ID: vec2.cross
Group: 2D Vector

This method returns the cross product between two vec2 types

Syntax

v1 = vec2( 1, 1 )
v2 = v1:cross( vec2(2, 2) )

Parameters

  • vector — compute the cross product with this vector

Returns

vec2, cross product of this vec2 and vector

Related: vec2

vec2.rotate( angle ) (method)

ID: vec2.rotate
Group: 2D Vector

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

  • angle — number, rotate this vector by angle in radians

Returns

vec2, rotated version of this vec2

Related: vec2

vec2.rotate90() (method)

ID: vec2.rotate90
Group: 2D Vector

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

Syntax

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

Returns

vec2, rotated version of this vec2

Related: vec2

vec2.angleBetween( v ) (method)

ID: vec2.angleBetween
Group: 2D Vector

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

Syntax

v1 = vec2( 1, 1 )
angle = math.deg( v1:angleBetween( vec2(5, 2) ) )

Parameters

  • vector — vec2, compute the angle between this vec2 and vector

Returns

number, angle between vec2 and vector in radians

Related: vec2

vec2.unpack() (method)

ID: vec2.unpack
Group: 2D Vector

This method returns each of a vector's components as separate values. It is useful for inputting vector types into functions which accept scalar values.

Syntax

v = vec2( 1, 2 )
x,y = v:unpack()

Returns

multiple, two values x, y

Examples

pos = vec2(20, 50)
translate( pos:unpack() )

Related: vec2

vec3 (type)

ID: vec3
Group: 3D Vector

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

  • x — number, x dimension of this vector
  • y — number, y dimension of this vector
  • z — number, z dimension of this vector

Related: vec3.dot, vec3.normalize, vec3.dist, vec3.distSqr, vec3.len, vec3.lenSqr, vec3.cross

vec3.dot( vector ) (method)

ID: vec3.dot
Group: 3D Vector

This method returns the scalar dot product between two vec3 types

Syntax

v1 = vec3( 1, 1, 1 )
x = v1:dot( v )

Parameters

  • vector — vec3, compute the dot product with this vector

Returns

number, dot product between this and vector

Related: vec3

vec3.normalize() (method)

ID: vec3.normalize
Group: 3D Vector

This method returns a normalized version of the vector

Syntax

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

Returns

vec3, normalized version of this vec3

Related: vec3

vec3.dist( vector ) (method)

ID: vec3.dist
Group: 3D Vector

This method returns the distance between two vec3 types

Syntax

v1 = vec3( 1, 1, 1 )
x = v1:dist( vec3(2, 2, 2) )

Parameters

  • vector — vec3, compute the distance to this vector

Returns

number, distance between this vec3 and vector

Related: vec3

vec3.distSqr( vector ) (method)

ID: vec3.distSqr
Group: 3D Vector

This method returns the squared distance between two vec3 types

Syntax

v1 = vec3( 1, 1, 1 )
x = v1:distSqr( vec3(2, 2, 2) )

Parameters

  • vector — vec3, compute the squared distance to this vector

Returns

number, squared distance between this vec3 and vector

Related: vec3

vec3.len() (method)

ID: vec3.len
Group: 3D Vector

This method returns the length of a vec3

Syntax

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

Returns

number, length of this vec3

Related: vec3

vec3.lenSqr() (method)

ID: vec3.lenSqr
Group: 3D Vector

This method returns the squared length of a vec3

Syntax

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

Returns

number, squared length of this vec3

Related: vec3

vec3.cross( vector ) (method)

ID: vec3.cross
Group: 3D Vector

This method returns the cross product between two vec3 types

Syntax

v1 = vec3( 1, 1 )
v2 = v1:cross( vec3(2, 2) )

Parameters

  • vector — vec3, compute the cross product with this vector

Returns

vec3, cross product of this vec3 and vector

Related: vec3

vec3.unpack() (method)

ID: vec3.unpack
Group: 3D Vector

This method returns each of a vector's components as separate values. It is useful for inputting vector types into functions which accept scalar values.

Syntax

v = vec3( 1, 2, 3 )
x,y,z = v:unpack()

Returns

multiple, three values x, y, z

Examples

myColor = vec3(255, 0, 255)
background( myColor:unpack() )

Related: vec3

vec4 (type)

ID: vec4
Group: 4D Vector

This type represents a 4D 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( vec4 ) that can be called on vec4 types, please see the related items below.

Syntax

vec4.x
vec4.y
vec4.z
vec4.w

vec4.r
vec4.g
vec4.b
vec4.a

myVec = vec4( 1.0, 2.0, 3.0, 1.0 )
v = vec4(1,2,3,0) + vec4(3,2,1,1)
v = vec4(1,1,1,1) * 5

Parameters

  • x — number, x dimension of this vector
  • y — number, y dimension of this vector
  • z — number, z dimension of this vector
  • w — number, w dimension of this vector

Related: vec4.dot, vec4.normalize, vec4.dist, vec4.distSqr, vec4.len, vec4.lenSqr

vec4.dot( vector ) (method)

ID: vec4.dot
Group: 4D Vector

This method returns the scalar dot product between two vec4 types

Syntax

v1 = vec4( 1, 1, 1, 1 )
x = v1:dot( v )

Parameters

  • vector — vec4, compute the dot product with this vector

Returns

number, dot product between this vec4 and vector

Related: vec4

vec4.normalize() (method)

ID: vec4.normalize
Group: 4D Vector

This method returns a normalized version of the vector

Syntax

v1 = vec4( 5, 5, 5, 5 )
v1 = v1:normalize()

Returns

vec4, normalized version of this vec4

Related: vec4

vec4.dist( vector ) (method)

ID: vec4.dist
Group: 4D Vector

This method returns the distance between two vec4 types

Syntax

v1 = vec4( 1, 1, 1, 1 )
x = v1:dist( vec4(2, 2, 2, 2) )

Parameters

  • vector — vec4, compute the distance to this vector

Returns

number, distance between this vec4 and vector

Related: vec4

vec4.distSqr( vector ) (method)

ID: vec4.distSqr
Group: 4D Vector

This method returns the squared distance between two vec4 types

Syntax

v1 = vec4( 1, 1, 1, 1 )
x = v1:distSqr( vec4(2, 2, 2, 2) )

Parameters

  • vector — vec4, compute the squared distance to this vector

Returns

number, squared distance between this vec4 and vector

Related: vec4

vec4.len() (method)

ID: vec4.len
Group: 4D Vector

This method returns the length of a vec4

Syntax

v1 = vec4( 2, 1, 0, 0 )
x = v1:len()

Returns

number, length of this vec4

Related: vec4

vec4.lenSqr() (method)

ID: vec4.lenSqr
Group: 4D Vector

This method returns the squared length of a vec4

Syntax

v1 = vec4( 2, 1, 0, 0 )
x = v1:lenSqr()

Returns

number, squared length of this vec4

Related: vec4

vec4.unpack() (method)

ID: vec4.unpack
Group: 4D Vector

This method returns each of a vector's components as separate values. It is useful for inputting vector types into functions which accept scalar values.

Syntax

v = vec4( 1, 2, 3, 4 )
x,y,z,w = v:unpack()

Returns

multiple, four values x, y, z, w

Examples

myColor = vec4(255, 0, 255, 255)
background( myColor:unpack() )

Related: vec4

bounds (type)

ID: bounds
Group: Bounds

A geometric utility type representing the rectangular bounding volume. Create a new bounds by giving it a minimum and maximum range as vec3s

Syntax

b = bounds(min, max)
b = bounds(vec3(0, 0, 0), vec3(1, 1, 1))

Parameters

  • min — vec3, the minimum x,y,z range of the area encapsulated by the bounding volume
  • max — vec3, the maximum x,y,z range of the area encapsulated by the bounding volume
  • valid — boolean, whether or not this bounds is valid (i.e. has zero or greater volume)
  • center — vec3, the center of the volume (i.e. half way between min and max)
  • offset — vec3, the offset of the volume (i.e. min)
  • size — vec3, the size of the volume (i.e. max - min)

Related: bounds.intersects, bounds.encapsulate, bounds.translate, bounds.set

bounds.intersects() (method)

ID: bounds.intersects
Group: Bounds

This method has two variants, the first bounds.intersects(other) checks to see whether two bounds values intersect

The second form, bounds.intersects(origin, dir) returns true if the given ray (specified by origin, dir intersects the bounds

Syntax

bounds.intersects(other)
bounds.intersects(origin, dir)

Parameters

  • other — bounds, another bounds value to test for intersection with
  • origin — vec3, point defining the origin of the ray to test for intersection with
  • dir — vec3, vector describing the ray to test for intersection with

Returns

boolean, whether this bounding volume intersects another or the given ray

Related: bounds

bounds.encapsulate() (method)

ID: bounds.encapsulate
Group: Bounds

This will expand the current bounds to include the given point (vec3)

Syntax

bounds.encapsulate(point)

Parameters

  • point — vec3, the bounds will be extended to enclose this point

Related: bounds

bounds.translate() (method)

ID: bounds.translate
Group: Bounds

Translate (move) the bounds by the specified offset

Syntax

bounds.translate(offset)

Parameters

  • offset — vec3, the bounds will offset by this amount

Related: bounds

bounds.set() (method)

ID: bounds.set
Group: Bounds

Reset the bounds using the specified min and max values

Syntax

bounds.set(min, max)

Parameters

  • min — vec3, the minimum x,y,z range of the area encapsulated by the bounding volume
  • max — vec3, the maximum x,y,z range of the area encapsulated by the bounding volume

Related: bounds

matrix (type)

ID: matrix
Group: Matrix

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

Returns

A new matrix with the given elements

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 - m2
m = m1 * 10
m = m1 / 10
m = -m1

checkEqual = m1 == m2

print( m1 )

Related: modelMatrix, matrix.rotate, matrix.translate, matrix.scale, matrix.inverse, matrix.transpose, matrix.determinant

matrix.rotate( r, x, y, z ) (method)

ID: matrix.rotate
Group: Matrix

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

  • angle — number, the rotation in degrees
  • axisX — number, the x component of the axis of rotation
  • axisY — number, the y component of the axis of rotation
  • axisZ — number, the z component of the axis of rotation

Returns

matrix, a matrix which rotates m by the specified rotation

Examples

m = matrix()

--Rotate about 0,0,1
rotated = m:rotate(30)

--Rotate by a given axis
rotated= m:rotate(30, 1, 0, 0)

Related: matrix

matrix.translate( x, y, z ) (method)

ID: matrix.translate
Group: Matrix

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

  • x — number, the x component of translation
  • y — number, the y component of translation
  • z — number, optional (defaults to 0) the z component of translation"

Returns

matrix, a matrix which translates m by the specified amount

Examples

m = matrix()
translated = m:translate(100,20,10)

Related: matrix

matrix.scale( x, y, z ) (method)

ID: matrix.scale
Group: Matrix

This method returns the matrix scaled by a translation matrix defining a scaling to each axis.

Syntax

scaled = m:scale( x, y, z )

Parameters

  • x — number, the x component of scale, or the uniform scale if no other components are given
  • y — number, optional, the y component of scale
  • z — number, optional, defaults to 1 if x and y are both given, otherwise x minus the z component of scale

Returns

matrix, a matrix which scales m by the specified amount

Examples

m = matrix()
s = m:scale(100,20,10)

--Uniform scaling
s = m:scale(5)

Related: matrix

matrix.inverse() (method)

ID: matrix.inverse
Group: Matrix

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

Returns

matrix, a matrix which inverts m

Related: matrix

matrix.transpose() (method)

ID: matrix.transpose
Group: Matrix

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

Returns

matrix, a matrix which is the transpose of m

Related: matrix

matrix.determinant() (method)

ID: matrix.determinant
Group: Matrix

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

number, a number equal to the determinant of m

Related: matrix

quat (type)

ID: quat
Group: Quaternion

This type represents a quaternion.

Syntax

quat.x
quat.y
quat.z
quat.w

myQuat = quat.eulerAngles(45,45,45)

Parameters

  • x — number, x dimension of this quaternion
  • y — number, y dimension of this quaternion
  • z — number, z dimension of this quaternion
  • w — number, w dimension of this quaternion

Related: quat.slerp, quat.angles, quat.angleAxis, quat.eulerAngles, quat.lookRotation, quat.fromToRotation

quat.eulerAngles( x, y, z ) (method)

ID: quat.eulerAngles
Group: Quaternion

Creates a new quaternion using 3 euler angles given in degrees.

Syntax

q = quat.eulerAngles(45,0,45)

Parameters

  • x — number, the amount of pitch in degrees
  • y — number, the amount of roll in degrees
  • z — number, the amount of yaw in degrees

Returns

quat, the resulting quaternion

Related: quat

quat.angleAxis( angle, axis ) (method)

ID: quat.angleAxis
Group: Quaternion

Creates a new quaternion using an angle and axis.

Syntax

q = quat.angleAxis(45, vec3(0,0,1))

Parameters

  • angle — float, the amount of rotation about the axis in degrees
  • axis — vec3, the axis to rotate around

Returns

quat, the resulting quaternion

Related: quat

quat.lookRotation( forward, up ) (method)

ID: quat.lookRotation
Group: Quaternion

Creates a new quaternion that 'looks' in a specified direction.

Syntax

q = quat.lookRotation( vec3(0,0,1), vec3(0,1,0) )

Parameters

  • forward — vec3, the direction to look at
  • up — vec3, the upwards direction used to orient the quaternion

Returns

quat, the resulting quaternion

Related: quat

quat.fromToRotation( from, to ) (method)

ID: quat.fromToRotation
Group: Quaternion

Creates a new quaternion that rotates between two directions.

Syntax

q = quat.fromToRotation( vec3(0,0,1), vec3(1,0,0) )

Parameters

  • from — vec3, the start direction
  • to — vec3, the the end direction

Returns

quat, the resulting quaternion

Related: quat

quat.slerp( q, t ) (method)

ID: quat.slerp
Group: Quaternion

Performs spherical interpolation (slerp) from this quaternion to another.

Syntax

q1 = quat.eulerAngles(0,0,0)
q2 = quat.eulerAngles(0,0,90)
q3 = q1:slerp(p2, 0.5)

Parameters

  • q — quat, the quaternion to interpolate towards
  • t — number, the amount of interpolation to perform

Returns

quat, the spherically interpolated quaternion

Related: quat

quat.angles() (method)

ID: quat.angles
Group: Quaternion

Extracts the euler angles from a quaternion and returns them as a vec3 in degrees.

Syntax

q = quat.eulerAngles(20,30,40)
angles = q:angles()

Returns

vec3, the euler angles for this quaternion in degrees

Related: quat

quat.normalized() (method)

ID: quat.normalized
Group: Quaternion

Returns a normalized copy of this quaternion

Syntax

q = quat.eulerAngles(20,30,40)
nq = q:normalized()

Returns

quat, a normalized version of this quaternion

Related: quat, quat.normalize

quat.normalize() (method)

ID: quat.normalize
Group: Quaternion

Normalize this quaternion

Syntax

q = quat.eulerAngles(20,30,40)
q:normalize()

Related: quat, quat.normalized

quat.conjugate() (method)

ID: quat.conjugate
Group: Quaternion

Return the conjugation of this quaternion

Syntax

q = quat.eulerAngles(20,30,40)
cq = q:conjugate()

Returns

quat, a conjugated version of this quaternion

Related: quat

quat.len() (method)

ID: quat.len
Group: Quaternion

Return the length of this quaternion

Syntax

q = quat.eulerAngles(20,30,40)
len = q:len()

Returns

number, the length of this quaternion

Related: quat, quat.lenSqr

quat.lenSqr() (method)

ID: quat.lenSqr
Group: Quaternion

Return the squared length of this quaternion

Syntax

q = quat.eulerAngles(20,30,40)
len2 = q:lenSqr()

Returns

number, the squared length of this quaternion

Related: quat, quat.len

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment