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.
Gravity
Gravity.x
Gravity.y
Gravity.zx— float, the amount of gravity in the x directiony— float, the amount of gravity in the y directionz— float, the amount of gravity in the z direction
Related: vec3, UserAcceleration
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.
UserAcceleration
UserAcceleration.x
UserAcceleration.y
UserAcceleration.zx— float, the amount of acceleration in the x directiony— float, the amount of acceleration in the y directionz— float, the amount of acceleration in the z direction
Related: vec3, Gravity
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.
RotationRate
RotationRate.x
RotationRate.y
RotationRate.zx— float, the amount of rotation around the x axisy— float, the amount of rotation around the y axisz— float, the amount of rotation around the z axis
Related: vec3, Gravity
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.
location.enable()function setup()
-- enable location updating
location.enable()
print(location)
endRelated: location.disable, location.available
ID: location.disable
Group: Location
Calling this function requests that the device should stop monitoring its physical location. Disabling location updates preserves battery power.
location.disable()Related: location.enable, location.available
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.
location.available()A boolean value specifying whether location data is available
Related: location.enable, location.disable
ID: location.distanceTo
Group: Location
This function returns the distance in meters from the current location (if available) to the specified latitude and longitude.
location.distanceTo(lat, lon)Distance in meters between the current location and specified coordinates
Related: location.distanceBetween
ID: location.distanceBetween
Group: Location
This function returns the distance in meters between two locations specified by the coordinates lat1, lon1, lat2, lon2.
location.distanceBetween(lat1, lon1, lat2, lon2)Distance in meters between the two specified coordinates
Related: location.distanceTo
ID: location.latitude
Group: Location
This value specifies the current latitude if location is available.
location.latitudeCurrent latitude, if available. Nil if not.
Related: location.longitude, location.enable
ID: location.longitude
Group: Location
This value specifies the current longitude if location is available.
location.longitudeCurrent longitude, if available. Nil if not.
Related: location.latitude, location.enable
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.
location.altitudeCurrent altitude, if available. Nil if not.
Related: location.enable
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.
location.horizontalAccuracyCurrent horizontal accuracy, if available. Nil if not.
Related: location.latitude, location.longitude
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.
location.verticalAccuracyCurrent vertical accuracy, if available. Nil if not.
Related: location.altitude
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.
location.speedCurrent speed, if available. Nil if not.
Related: location.course
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.
location.courseCurrent course, if available. Nil if not.
Related: location.speed
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.
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, ... )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' keycallback— function, a function to call when this tween has completed
table, returns a tween identifier that can be used to stop, reset or play the tween
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
ID: tween.stop
Group: Animating Values
Stops the tween specified by id. This does not reset the subject's values to their initial state.
tween.stop( id )id— table, the id of the tween to stop
point = { x = 10, y = 10}
id = tween(1, point, {x = 100})
tween.stop(id)Related: tween.stop, tween.stopAll, tween.reset, tween.resetAll
ID: tween.stopAll
Group: Animating Values
Stops all active tweens without resetting them.
tween.stopAll()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
ID: tween.reset
Group: Animating Values
Stops the tween specified by id and resets the subject's values to their initial state.
tween.reset( id )id— table, the id of the tween to reset
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
ID: tween.resetAll
Group: Animating Values
Resets all active tweens, returning all subject's to their state before the animation.
tween.resetAll()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
ID: tween.play
Group: Animating Values
Plays the tween specified by id. This does not reset the subject's values to their initial state.
tween.play( id )id— table, the id of the tween to play
point = { x = 10, y = 10}
id = tween(1, point, {x = 100})
function pauseTween(id)
tween.stop(id)
end
function resumeTween(id)
tween.play(id)
endRelated: tween.stop, tween.stopAll, tween.reset, tween.resetAll
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.
tween.delay( duration )
tween.delay( duration, callback )
tween.delay( duration, callback, ... )duration— number, the duration of the delaycallback— function, optional callback function
table, returns the tween identifier for the delay
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
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.
tween.sequence( t1, t2, t3, ... )t1— the id of a tween in the sequence
table, returns the tween identifier for the first tween in the sequence
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
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.
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, ... )time— float, the duration of the tweensubject— table or userdata, the object to animatetargets— table, an array of tables containing key-value pairs for each point along the pathoptions— table, may contain a loop type specified under the 'loop' key and an easing type specified under the 'easing' keyeasing— function, one of the easing functions specified intween.easingcallback— function, triggered when the animation is complete
table, returns a tween identifier that can be used to pause, reset or stop the tween
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
ID: tween.loop.once
Group: Looping Types
Plays the tween once. This is the default loop type.
tween.loop.onceRelated: tween
ID: tween.loop.forever
Group: Looping Types
Plays the tween over and over again, restarting it each time.
tween.loop.foreverRelated: tween
ID: tween.loop.pingpong
Group: Looping Types
Plays the tween backwards after it finishes, and then continues to repeat it back and forth.
tween.loop.pingpongRelated: tween
ID: tween.easing.linear
Group: Easing Types
tween.easing.linearRelated: tween
ID: tween.easing.quadIn
Group: Easing Types
tween.easing.quadInRelated: tween
ID: tween.easing.quadOut
Group: Easing Types
tween.easing.quadOutRelated: tween
ID: tween.easing.quadInOut
Group: Easing Types
tween.easing.quadInOutRelated: tween
ID: tween.easing.quadOutIn
Group: Easing Types
tween.easing.quadOutInRelated: tween
ID: tween.easing.cubicIn
Group: Easing Types
tween.easing.cubicInRelated: tween
ID: tween.easing.cubicOut
Group: Easing Types
tween.easing.cubicOutRelated: tween
ID: tween.easing.cubicInOut
Group: Easing Types
tween.easing.cubicInOutRelated: tween
ID: tween.easing.cubicOutIn
Group: Easing Types
tween.easing.cubicOutInRelated: tween
ID: tween.easing.quartIn
Group: Easing Types
tween.easing.quartInRelated: tween
ID: tween.easing.quartOut
Group: Easing Types
tween.easing.quartOutRelated: tween
ID: tween.easing.quartInOut
Group: Easing Types
tween.easing.quartInOutRelated: tween
ID: tween.easing.quartOutIn
Group: Easing Types
tween.easing.quartOutInRelated: tween
ID: tween.easing.quintIn
Group: Easing Types
tween.easing.quintInRelated: tween
ID: tween.easing.quintOut
Group: Easing Types
tween.easing.quintOutRelated: tween
ID: tween.easing.quintInOut
Group: Easing Types
tween.easing.quintInOutRelated: tween
ID: tween.easing.quintOutIn
Group: Easing Types
tween.easing.quintOutInRelated: tween
ID: tween.easing.expoIn
Group: Easing Types
tween.easing.expoInRelated: tween
ID: tween.easing.expoOut
Group: Easing Types
tween.easing.expoOutRelated: tween
ID: tween.easing.expoInOut
Group: Easing Types
tween.easing.expoInOutRelated: tween
ID: tween.easing.expoOutIn
Group: Easing Types
tween.easing.expoOutInRelated: tween
ID: tween.easing.sineIn
Group: Easing Types
tween.easing.sineInRelated: tween
ID: tween.easing.sineOut
Group: Easing Types
tween.easing.sineOutRelated: tween
ID: tween.easing.sineInOut
Group: Easing Types
tween.easing.sineInOutRelated: tween
ID: tween.easing.sineOutIn
Group: Easing Types
tween.easing.sineOutInRelated: tween
ID: tween.easing.backIn
Group: Easing Types
tween.easing.backInRelated: tween
ID: tween.easing.backOut
Group: Easing Types
tween.easing.backOutRelated: tween
ID: tween.easing.backInOut
Group: Easing Types
tween.easing.backInOutRelated: tween
ID: tween.easing.backOutIn
Group: Easing Types
tween.easing.backOutInRelated: tween
ID: tween.easing.bounceIn
Group: Easing Types
tween.easing.bounceInRelated: tween
ID: tween.easing.bounceOut
Group: Easing Types
tween.easing.bounceOutRelated: tween
ID: tween.easing.bounceInOut
Group: Easing Types
tween.easing.bounceInOutRelated: tween
ID: tween.easing.bounceOutIn
Group: Easing Types
tween.easing.bounceOutInRelated: tween
ID: tween.easing.elasticIn
Group: Easing Types
tween.easing.elasticInRelated: tween
ID: tween.easing.elasticOut
Group: Easing Types
tween.easing.elasticOutRelated: tween
ID: tween.easing.elasticInOut
Group: Easing Types
tween.easing.elasticInOutRelated: tween
ID: tween.easing.elasticOutIn
Group: Easing Types
tween.easing.elasticOutInRelated: tween
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
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
scene = craft.scene()main— scene [static], the main scene which when set will automatically update and draw each framecamera— 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 offfogNear— number, the distance where fog beginsfogFar— number, the distance where fog reaches maximum densityfogColor— color, the color of the fogrenderBatchCount— 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
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
endRelated: craft.renderer, craft.camera
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.
myEntity = scene:entity()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 spaceworldPosition— vec3, the position of this entity in world coordinate spacerotation— quat, the rotation of this entity in local coordinate spaceworldRotation— quat, the rotation of this entity in world coordinate spacescale— vec3, the scale of this entity in local coordinate spacex— float, the x position of this entity in local coordinate spacey— float, the y position of this entity in local coordinate spacez— float, the z position of this entity in local coordinate spaceeulerAngles— vec3, the rotation of this entity in local coordinate space expressed in euler anglesparent— entity, the parent of this entity (in the transform hierarchy)children— table [readonly], an array of children entities attached to this entityactive— bool, turn on and off to enable and disable entity in the scene
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
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.
myEntity:add( craft.renderer, myModel )
myEntity:add( craft.shape.box, vec3(1,1,1) )
myEntity:add( LuaClass, p1, p2, p3, ... )type— type, the type of component to add to this entity
object, the component added to this entity
-- 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()
endRelated: craft.entity
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.
myEntity:get( craft.renderer )
myEntity:get( craft.shape.box )
myEntity:get( craft.rigidbody )
myEntity:get( LuaClass )type— type, the type of component to get from this entity
object, the requested component (or nil if it does not exist)
Related: craft.entity, entity.add, entity.remove
ID: entity.remove
Group: Entities
Removes a component of a particular type attached to this entity, if it exists.
myEntity:remove( craft.renderer )
myEntity:remove( craft.shape.box )
myEntity:get( craft.rigidbody )
myEntity:remove( LuaClass )type— type, the type of component to remove from this entity
Related: craft.entity, entity.add, entity.remove
ID: entity.destroy
Group: Entities
Marks this entity for destruction in the next frame. Any children will also be marked for destruction.
myEntity:destroy()Related: craft.entity
ID: entity.transformPoint
Group: Entities
Transforms a point from local space into world space using this entity's transform.
myEntity:transformPoint(point)point— vec3, the point to transform
vec3, the transformed point
Related: craft.entity
ID: entity.inverseTransformPoint
Group: Entities
Transforms a point from world space into local space using this entity's transform.
myEntity:inverseTransformPoint(point)point— vec3, the point to transform
vec3, the transformed point
Related: craft.entity
ID: entity.transformDirection
Group: Entities
Transforms a direction from local space into world space using this entity's transform.
myEntity:transformDirection(point)direction— vec3, the direction to transform
vec3, the transformed direction
Related: craft.entity
ID: entity.inverseTransformDirection
Group: Entities
Transforms a direction from world space into local space using this entity's transform.
myEntity:inverseTransformDirection(direction)direction— vec3, the direction to transform
Related: craft.entity
ID: craft.camera
Group: Rendering
A component used to draw the scene from its point of view.
myEntity:add(craft.camera, fov, nearPlane, farPlane, false)
myEntity:add(craft.camera, orthoSize, nearPlane, farPlane, true)fieldOfView— float, the field of view of the camera in degreesortho— bool, orthographic rendering mode for this cameranearPlane— 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 cameraentity— entity, the entity that the camera is attached to
-- create a new entity and add a camera to it
camera = scene:entity():add(craft.camera, 45, 0.1, 1000, false)Related: craft.entity
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.
myCamera:screenToWorld( position )position— vec3, the position to convert to world space
vec3
Related: craft.camera
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.
origin, dir = myCamera:screenToRay( position )position— vec2, the position to generate a ray with
vec3, vec3
Related: craft.camera
ID: camera.worldToScreen
Group: Rendering
Converts a position given in world coordinates to screen coordinates relative to this camera.
myCamera:worldToScreen( screenPos )position— vec3, the position to convert to screen space
vec2
Related: craft.camera
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.
myCamera:viewport(x, y, width, height)
x, y, w, h = myCamera:viewport()x— float, the x position of the viewporty— float, the y position of the viewportwidth— float, the width viewportheight— float, height of the viewport
x, y, w, h
Related: craft.camera
ID: camera.addPostEffect
Group: Rendering
Adds a post processing effect to this camera
local bloom = craft.bloomEffect()
myCamera.hdr = true
myCamera:addPostEffect( bloom )postEffect— postEffect, the post processing effect to add to this camera
Related: craft.camera
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
local bloom = craft.bloomEffect()
myCamera.hdr = true
myCamera:addPostEffect( bloom )enabled— boolean, enables or disables the effectiterations— integer, the number of iterations of blur to apply, more iterations increase the blurthreshold— number, the threshold for color intensity before bloom begins to applysoftThreshold— number, the soft threshold parameter for adjusting the bloom curve (also known as the knee)intensity— number, the intensity of the bloom effect
scene = craft.scene()
cam = scene.camera:get(craft.camera)
cam.hdr = true
local bloom = craft.bloomEffect()
cam:addPostEffect( bloom )Related: craft.entity
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.
myEntity:add(craft.renderer, model)material— material, the material to apply to this renderermodel— model, the model to render
-- 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
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.
myEntity:add(craft.light, DIRECTIONAL)
myEntity:add(craft.light, SPOT)
myEntity:add(craft.light, POINT)type— the type of light, can be DIRECTIONAL, SPOT, POINTcolor— color, the color of the lightintensity— 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
-- 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
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.
DIRECTIONALint
Related: craft.light
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.
SPOTint
Related: craft.light
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.
POINTint
Related: craft.light
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.
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)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)
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 = 1Related: craft.entity, craft.renderer, craft.model
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.
myModel = craft.model()
myModel = craft.model( asset )vertexCount— int, the number of vertices in this modelindexCount— int, the number of indices in this modelpositions— array, the positions of the vertices of this modelnormals— array, the normals of the vertices of this modelcolors— array, the colors of the vertices of this modeluvs— array, the uvs of the vertices of this modelindices— array, the primitive indices of this model used to form trianglesmaterial— material, the material for this model (overridden by renderer materials)
-- 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 = indicesRelated: craft.renderer, craft.material
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).
myModel = craft.model.cube()
myModel = craft.model.cube(size)
myModel = craft.model.cube(size, offset)size— vec3, the size of the cubeoffset— vec3, the offset of the center of the cube
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.
myModel = craft.model.icosphere(radius)
myModel = craft.model.icosphere(radius, subdivisions)
myModel = craft.model.icosphere(radius, subdivisions, flat)radius— float, the radius of the icospheresubdivisions— int, the number of subdivisions to apply the base icosphere
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).
myModel = craft.model.plane()
myModel = craft.model.plane(size)
myModel = craft.model.plane(size, offset)size— vec2, the size of the plane (x, z dimensions)offset— vec3, the offset of the center of the plane
ID: model.resizeVertices
Group: Rendering
Sets the number of vertices in the model.
myModel:resizeVertices( size )size— int, the number of vertices
Related: craft.model, model.resizeIndices
ID: model.resizeIndices
Group: Rendering
Sets the number of indices in the model where each set of 3 indices forms a triangle.
myModel:resizeIndices( size )size— int, the number of indices
Related: craft.model, model.resizeVertices
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).
myModel:position( index )
myModel:position( index, p )
myModel:position( index, x, y, z )index— int,
Related: craft.model, model.resizeVertices
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).
x, y, z = myModel:normal( index )
myModel:normal( index, n )
myModel:normal( index, x, y, z )index— int,
Related: craft.model, model.resizeVertices, model.position
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).
r, g, b, a = myModel:color( index )
myModel:color( index, c )
myModel:color( index, r, g, b, a )index— int,
Related: craft.model, model.resizeVertices, model.position, model.normal, model.uv
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).
u, v = myModel:uv( index )
myModel:uv( index, p )
myModel:uv( index, u, v )index— int, index of the vertex to access
Related: craft.model, model.resizeVertices, model.position, model.normal, model.color
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
myModel.submeshCountRelated: craft.model, craft.material, model.setMaterial, model.getMaterial
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
mat = myModel:getMaterial()
mat = myModel:getMaterial( index )index— int, index of the submesh to access, starting at 1
Related: craft.model, craft.material, model.setMaterial
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
myModel:setMaterial( material )
myModel:setMaterial( material, index )material— Craft material to apply to the submesh at this indexindex— int, index of the submesh to access, starting at 1
Related: craft.model, craft.material, model.getMaterial
ID: model.addElement
Group: Rendering
Adds a variable number of indices to the model. Each index must be within the range 1..model.vertexCount
myModel:addElement( index1, index2, ..., indexN )index— int,
Related: craft.model, model.resizeVertices, model.position, model.normal, model.color, model.indices
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
myModel:clear()Related: craft.model
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
myModel:split()
myModel:split( index )index— int, index of the submesh to access, starting at 1
Related: craft.model
ID: craft.physics
Group: Physics
The system governing all 3D physics in a scene.
paused— bool, use to pause and unpause the physics simulationgravity— vec3, the current force of gravity effecting all rigidbodies (measured in ms^2)
ID: physics.raycast
Group: Physics
Performs a raycast in the scene against any rigidbodies with attached shapes.
scene.physics:raycast(origin, direction, distance)
scene.physics:raycast(origin, direction, distance, group)
scene.physics:raycast(origin, direction, distance, group, mask)origin— vec3, the origin of the raydirection— vec3, the direction of the raydistance— float, the maximum distance the ray can travelgroup— int, the group of the ray (used for filtering)mask— int, the mask of the ray (used for filtering)
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)
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.
scene.physics:spherecast(origin, direction, distance, radius)
scene.physics:spherecast(origin, direction, distance, radius, group)
scene.physics:spherecast(origin, direction, distance, radius, group, mask)origin— vec3, the origin of the spherecastdirection— vec3, the direction of the spherecastdistance— float, the maximum distance the spherecast can travelradius— float, the radius of the spherecastgroup— bitmask, the group of the ray (used for filtering)mask— bitmask, the mask of the ray (used for filtering)
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
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.
myRigidbody = myEntity:add( craft.rigidbody, STATIC )
myRigidbody = myEntity:add( craft.rigidbody, KINEMATIC )
myRigidbody = myEntity:add( craft.rigidbody, DYNAMIC, mass )type— the type of the body, can be STATIC, DYNAMIC or KINEMATICmass— float, the mass of the rigid body in kilogramscenterOfMass— vec3, the center of mass of the rigid body in world spacelinearVelocity— vec3, the current linear velocity of the body in meters per secondangularVelocity— vec3, the angular velocity of the body in degrees per secondawake— bool, is the rigid body currently awakesleepingAllowed— bool, is sleeping allowed for this rigid bodylinearDamping— float, linear damping factor, slows rigid body movement over timeangularDamping— float, angular damping factor, slows rigid body rotation over timefriction— float, sliding friction factorrollingFriction— float, rolling friction factorrestitution— float, restitution factor, the bounceyness of this rigid bodygroup— bitmask, the collision filtering group for this rigid bodymask— bitmask, the collision filtering mask for this rigid body
-- 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
ID: DYNAMIC
Group: Physics
This constant specifies the dynamic body type. Dynamic bodies move under the influence of collisions, forces, joints and gravity.
DYNAMICint
Related: craft.rigidbody
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.
STATICint
Related: craft.rigidbody
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.
KINEMATICint
Related: craft.rigidbody
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.
myBody:applyForce( force )
myBody:applyForce( force, worldPoint )force— vec3, the amount of force (in newtons per second) to apply as a vectorworldPoint— vec3, the point to apply the force from, in world coordinates
Related: craft.rigidbody, rigidbody.applyTorque
ID: rigidbody.applyTorque
Group: Physics
Applies torque to this rigidbody.
myBody:applyTorque( torque )force— vec3, the amount of torque (in newton meters per second) to apply as a vector
Related: craft.rigidbody, rigidbody.applyForce
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.
myShape = myEntity:add(craft.shape.box, size)
myShape = myEntity:add(craft.shape.box, size, offset)size— vec3, the size of the boxoffset— vec3, the offset of the box (center)
-- 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
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.
myShape = myEntity:add(craft.shape.sphere, radius)
myShape = myEntity:add(craft.shape.sphere, radius, offset)-- 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
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.
myShape = myEntity:add(craft.shape.model, model)-- 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
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.
myShape = myEntity:add(craft.shape.capsule, radius, height)-- 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
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.
craft.voxelscoordinates— vec3, the viewing coordinates to stream voxels around (in world coordinates)visibleRadius— float, the radius (in chunks) to stream around the viewing coordinatesvisibleChunks— int, the number of chunks that are loaded and potentially visible in the scenegeneratingChunks— int, the number of chunks that are currently being generatedmeshingChunks— int, the number of chunks that are currently being meshed (turned into models)
-- 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
ID: craft.voxels.resize
Group: Voxels
Resizes the voxel terrain to a specified size divided into chunks, which can be generated and streamed efficiently.
scene.voxels:resize( vec3(100, 1, 100) )
scene.voxels:resize( vec3(100, 1, 100), vec3(16, 128, 16) )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
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.
scene.voxels:generate(generationCode, generationFunction)generationCode— string, the lua code to use for multi-threaded generationgenerationFunction— string, the name of the function withingenerationCodeto use
Related: craft.voxels
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.
scene.voxels:get ( coord, key )
scene.voxels:get ( coord, key1, key2, ... keyN )
scene.voxels:get ( coord, keyArray )coord— vec3 or (x,y,z), the coordinate of the block (in world coordinates) to get the data fromkey— the key of the data to get for this block
multiple, the values associated with the block's keys (or nil if it does not exist)
Related: craft.scene
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.
scene.voxels:set ( coord, key, value )
scene.voxels:set ( coord, key1, value1, ... keyN, valueN )
scene.voxels:set ( coord, keyValueTable )coord— vec3 or (x,y,z), the coordinate of the block (in world coordinates) to set the data forkey— the key of the data to set for this blockvalue— the value to set the data to
Related: craft.block
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.
scene.voxels:fill ( key )
scene.voxels:fill ( key1, key2, ... keyN )
scene.voxels:fill ( keyArray )key— the key of the data to use for the fillvalue— the value of the data to use for the fill
Related: craft.scene
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
scene.voxels:fillStyle ( style )style— the style to use
Related: craft.scene
ID: craft.voxels.block
Group: Voxels
Sets a single block using the current fill() and fillStyle() settings.
scene.voxels:block ( coord )coord— vec3 or (x,y,z), the coordinate to place the block
Related: craft.block
ID: craft.voxels.sphere
Group: Voxels
Sets a sphere shaped array of blocks using the coord and radius
scene.voxels:sphere ( coord, radius )
scene.voxels:sphere ( x, y, z, radius )coord— vec3 or (x,y,z), the coordinate of the sphere to placeradius— float, the radius of the sphere to place
Related: craft.block
ID: craft.voxels.box
Group: Voxels
Sets a box shaped array of blocks using the minimum and maximum coordinates supplied.
scene.voxels:box ( min, max )
scene.voxels:box ( x1, y1, z1, x2, y2, z2 )min— vec3 or (x,y,z), the coordinate of the minimum corner of the boxmax— vec3 or (x,y,z), the coordinate of the maximum corner of the box
Related: craft.block
ID: craft.voxels.line
Group: Voxels
Sets a line shaped array of blocks using the minimum and maximum coordinates supplied.
scene.voxels:line ( start, end )
scene.voxels:line ( x1, y1, z1, x2, y2, z2 )start— vec3 or (x,y,z), the coordinate of the start of the lineend— vec3 or (x,y,z), the coordinate of the end of the line
Related: craft.block
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).
scene.voxels:updateBlock ( coord, ticks )
scene.voxels:updateBlock ( x, y, z, ticks )coord— vec3 or (x,y,z), the coordinate of the block to updateticks— ticks, the number of ticks to wait for the update
Related: craft.block
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.
scene.voxels:raycast( start, direction, distance, callback )origin— vec3, the origin of the raydirection— vec3, the direction of the raydistance— vec3, the maximum distance the ray can travelcallback— function, a callback that will be called for each voxel encountered
-- 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
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).
scene.voxels:iterateBounds( min, max, callback )min— vec3 or (x,y,z), the coordinate of the minimum corner of the boxmax— vec3 or (x,y,z), the coordinate of the maximum corner of the boxcallback— function, the function to callback for each block encountered
Related: craft.block
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.
scene.voxels:isRegionLoaded( min, max )min— vec3 or (x,y,z), the coordinate of the minimum corner of the boxmax— vec3 or (x,y,z), the coordinate of the maximum corner of the box
Related: craft.block
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.
scene.voxels:enableStorage( storageName )storageName— string, the name of the storage folder to use
Related: craft.block
ID: craft.voxels.disableStorage
Group: Voxels
Disables storage.
scene.voxels:disableStorage()Related: craft.block
ID: craft.voxels.deleteStorage
Group: Voxels
Deletes a particular storage folder (if it exists).
scene.voxels:deleteStorage( storageName )storageName— string, the name of the storage folder to delete
Related: craft.block
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.
id— int, the id of this block typename— string, the name of this block typestate— type, the state of this blockgeometry— int, the type of geometry to generate, can be EMPTY, SOLID, TRANSPARENT or TRANSLUCENTrenderPass— int, the type of render pass to use, can be OPAQUE or TRANSLUCENTtinted— bool, whether this block type supports tinting (changing color)scripted— bool, whether this block type supports scriptingdynamic— bool, whether this block type is dynamicx— 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
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.
myBlock:get ( key )
myBlock:get ( key1, key2, ... keyN )
myBlock:get ( keyArray )key— the key of the data to set on this block
Related: craft.block
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.
myBlock:set ( key, value )
myBlock:set ( key1, value1, ... keyN, valueN )
myBlock:set ( keyValueTable )key— the key of the data to set on this blockvalue— the value to set the data to
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)
endRelated: craft.block
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.
myEntity:add(craft.volume, x, y, z)-- create a new entity
entity = scene:entity()
entity:add(craft.volume, 10, 10, 10)Related: craft.entity
ID: volume.size
Group: Voxels
Returns the size of this volume in voxels as 3 components (x, y, z).
sx, sy, sz = myVolume:size()size of the volume as 3 separate values
entity = scene:entity()
volume = entity:add(craft.volume, 10, 10, 10)
-- outputs: 10 10 10
print(volume:size())Related: craft.volume
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.
myVolume:get ( key )
myVolume:get ( key1, key2, ... keyN )
myVolume:get ( keyArray )coord— vec3 or (x,y,z), the coordinate of the block (in world coordinates) to get the data fromkey— the key of the data to get for this block
multiple, the values associated with the block's keys (or nil if it does not exist)
Related: craft.scene
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.
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 )x— number, the x location of the block to sety— number, the y location of the block to setz— number, the z location of the block to set
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
ID: volume.resize
Group: Voxels
Resizes the volume to a specific size.
myVolume:resize( x, y, z )x— float, the width of the volumey— float, the height of the volumez— float, the depth of the volume
Related: craft.volume
ID: volume.load
Group: Voxels
Loads a saved volume.
myVolume:load( asset.documents.MyVoxelModel )asset— asset key, the name of the asset to load
Related: craft.volume
ID: volume.save
Group: Voxels
Saves a volume as a voxel asset.
myVolume:save( asset.documents.MyVoxelModel )asset— asset key, the name of the asset to save
Related: craft.volume
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.
isSupported— bool [static, readonly], use to determine if your device supports ARisFaceTrackingSupported— bool [static, readonly], use to determine if your device supports AR face trackingisRunning— bool [readonly], use to determine if AR is currenly activeplaneDetection— bool, enable and disable plane detectiontrackingState— enum [readonly], the current tracking state - can beAR_NOT_AVAILABLE,AR_LIMITEDandAR_NORMALtrackingStateReason— enum [readonly], the reason for the current tracking state (ifAR_LIMITED) - can beAR_NONE,AR_EXCESSIVE_MOTIONandAR_INSUFFICIENT_FEATURESdidAddAnchors— function, the function to call when one or more anchors is added to the AR systemdidUpdateAnchors— function, the function to call when one or more anchors is updateddidRemoveAnchors— function, the function to call when one or more anchors is removed
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.
scene.ar:run()
scene.ar:run(AR_WORLD_TRACKING)
scene.ar:run(AR_FACE_TRACKING)trackingType— constant, the type of tracking to use (i.e.AR_WORLD_TRACKINGorAR_FACE_TRACKING)
Related: craft.ar, AR_WORLD_TRACKING, AR_FACE_TRACKING
ID: ar.pause
Group: AR
Pauses AR.
scene.ar:pause()Related: craft.ar
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)
scene.ar:hitTest( screenPoint )screenPoint— vec2, the screen point to check for hits in the AR worldoptions— bitmask, the options to use for finding things in the AR world
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
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.
scene.ar:makeFaceModel(blendShapes)blendShapes— table, the table of blend shapes to use to construct the model
Related: craft.ar, craft.ar.anchor, AR_FACE_TRACKING
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.
type— int, the type of anchoridentifier— string, the unique identifier for this anchorposition— 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)
ID: craft.ar.hitTestResult
Group: AR
A hit test result that is returned by the ar:hitTest() function.
The type of hittest can be
type— int, the type of hit testidentifier— string, the unique identifier for this anchorposition— 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
ID: AR_WORLD_TRACKING
Group: AR
This constant specifies the AR world tracking session type used in the ar.run() method.
AR_WORLD_TRACKINGint
Related: craft.ar, AR_FACE_TRACKING
ID: AR_FACE_TRACKING
Group: AR
This constant specifies the AR face tracking session type used in the ar.run() method.
AR_FACE_TRACKINGint
Related: craft.ar, AR_WORLD_TRACKING
ID: AR_NOT_AVAILABLE
Group: AR
This constant specifies that AR world tracking is not currently available. Returned by ar.trackingState.
AR_NOT_AVAILABLEint
Related: craft.ar
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.
AR_LIMITEDint
Related: craft.ar
ID: AR_NORMAL
Group: AR
This constant specifies that AR world tracking is currently normal. Returned by ar.trackingState.
AR_NORMALint
Related: craft.ar
ID: AR_NONE
Group: AR
This constant specifies that AR world tracking is not currently limited. Returned by ar.trackingStateReason.
AR_NONEint
Related: craft.ar
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.
AR_EXCESSIVE_MOTIONint
Related: craft.ar
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.
AR_INSUFFICIENT_FEATURESint
Related: craft.ar
ID: AR_FEATURE_POINT
Group: AR
Used by ar:hitTest as a mask for detecting feature points during hit test.
AR_FEATURE_POINTint
Related: craft.ar
ID: AR_ESTIMATED_PLANE
Group: AR
Used by ar:hitTest as a mask for detecting estimated planes during hit test.
AR_ESTIMATED_PLANEint
Related: craft.ar
ID: AR_EXISTING_PLANE
Group: AR
Used by ar:hitTest as a mask for detecting existing planes during hit test.
AR_EXISTING_PLANEint
Related: craft.ar
ID: AR_EXISTING_PLANE_CLIPPED
Group: AR
Used by ar:hitTest as a mask for detecting existing planes (clipped to edges) during hit test.
AR_EXISTING_PLANE_CLIPPEDint
Related: craft.ar
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.
ID: craft.noise.perlin
Group: Noise
A perlin noise generator module. Zero inputs.
n = craft.noise.perlin()octaves— int, the number of octaves, controlling the detail of the noisefrequency— float, the frequency of the first octavepersistence— float, the persistence controls how rough the noise produced islacunarity— float, the lucunarity controls the multiplier between successive octavesseed— int, the seed
local n = craft.noise.perlin()
local value = n:getValue(x,y,z)ID: craft.noise.rigidMulti
Group: Noise
A rigid multi-fractal noise generator module. Zero inputs.
n = craft.noise.rigidMulti()octaves— int, the number of octaves, controlling the detail of the noisefrequency— float, the frequency of the first octavelacunarity— float, the lucunarity controls the multiplier between successive octavesseed— int, the seed
local n = craft.noise.rigidMulti()
local value = n:getValue(x,y,z)ID: craft.noise.billow
Group: Noise
A billow noise generator module. Zero inputs.
n = craft.noise.billow()octaves— int, the number of octaves, controlling the detail of the noisefrequency— float, the frequency of the first octavepersistence— float, the persistence controls how rough the noise produced islacunarity— float, the lucunarity controls the multiplier between successive octavesseed— int, the seed
local n = craft.noise.billow()
local value = n(x,y,z)ID: craft.noise.turbulence
Group: Noise
Transformer module that distorts input using turbulent noise. One input.
n = craft.noise.turbulence()frequency— float, the frequency of the turbulenceroughness— float, how rough the turbulence ispower— float, how much distortion to applyseed— int, the seed
local n1 = craft.noise.perlin()
local n2 = craft.noise.turbulence()
n2:setSource(0, n1)
local value = n(x,y,z)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.
n = craft.noise.cache()ID: craft.noise.const
Group: Noise
Constant noise module. Returns a constant value at any location. Zero inputs.
n = craft.noise.const(value)local n = craft.noise.const(10)
-- Always returns 10
local value = n(x,y,z)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.
n = craft.noise.select()ID: craft.noise.gradient
Group: Noise
Returns a gradient in the y-axis mapped from zero to one. Zero inputs.
n = craft.noise.gradient()ID: craft.noise.min
Group: Noise
Returns the minimum of two noise modules. Two inputs.
n = craft.noise.min()ID: craft.noise.max
Group: Noise
Returns the maximum of two noise modules. Two inputs.
n = craft.noise.max()ID: craft.noise.add
Group: Noise
Returns the addition of two noise modules. Two inputs.
n = craft.noise.add()ID: craft.noise.multiply
Group: Noise
Returns the multiplication of two noise modules. Two inputs.
n = craft.noise.multiply()ID: craft.noise.invert
Group: Noise
Returns the negative of the source noise module. One inputs.
n = craft.noise.invert()ID: craft.noise.abs
Group: Noise
Returns the absolute version of the source noise module. One input.
n = craft.noise.abs()ID: craft.noise.merge
Group: Noise
Returns the first non-zero value of two noise modules. Two inputs.
n = craft.noise.merge()ID: craft.noise.scaleOffset
Group: Noise
Scales and offsets the output of a noise module. One input.
n = craft.noise.scaleOffset()ID: craft.noise.displace
Group: Noise
Displaces the coordinates of a noise module using three other noise modules. Four inputs.
n = craft.noise.displace()ID: craft.noise.scale
Group: Noise
Scales the coordinates of the input source module. One input.
n = craft.noise.scale()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.
viewer.mode = STANDARD |
FULLSCREEN |
FULLSCREEN_NO_BUTTONSmode— EitherSTANDARD,FULLSCREENorFULLSCREEN_NO_BUTTONS
The current viewer mode
function setup()
--Set the viewer to full screen
viewer.mode = FULLSCREEN
endfunction setup()
--Set the viewer to standard
--i.e. visible parameters and output
viewer.mode = STANDARD
endfunction setup()
--Set the viewer to fullscreen
--Hide back/pause/play buttons
viewer.mode = FULLSCREEN_NO_BUTTONS
endRelated: STANDARD, FULLSCREEN, FULLSCREEN_NO_BUTTONS
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
viewer.framerate = 30framerate— Either 0, 15, 30, 60 or 120
The preferred framerate
function setup()
--Set the viewer to a low framerate
viewer.preferredFPS = 15
endID: 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)
viewer.pointerLocked = truepointerLocked—trueorfalse
Whether pointer locking is desired
function setup()
-- Lock the pointer
viewer.pointerLocked = true
endID: 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
viewer.isPresentingisPresenting— true if the viewer is presenting a view
Whether the viewer is presenting a view
function draw()
if viewer.isPresenting == false then
-- Do something
end
endID: viewer.runtime
Group: Display Modes
Returns the runtime type between LEGACY and MODERN.
viewer.runtimeruntime— LEGACY if using the legacy runtime type MODERN if using the modern runtime type
Whether the runtime type is LEGACY or MODERN
function draw()
if viewer.runtime == MODERN then
style.strokeWidth(5)
else
strokeWidth(5)
end
endID: 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.
viewer.showWarnings = falseWhether warnings should be displayed
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.
FULLSCREENRelated: viewer.mode
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.
viewer.mode = STANDARDRelated: viewer.mode
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.
viewer.mode = FULLSCREEN_NO_BUTTONSRelated: viewer.mode, viewer.close
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.
function setup()
end
function sizeChanged( newWidth, newHeight )
-- This function gets called when
-- the view size changes
endRelated: layout.horizontal, layout.vertical, layout.safeArea, CurrentOrientation
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.
top— number, the safe area inset for the top of the viewerleft— number, the safe area inset for the left of the viewerbottom— number, the safe area inset for the bottom of the viewerright— number, the safe area inset for the right of the viewer
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)
endRelated: layoutOverview
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
-- 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
endRelated: layoutOverview, layout.vertical
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
ID: layout.COMPACT
Group: Layout
This value indicates a compact layout environment for the specified dimension
Related: layoutOverview, layout.horizontal, layout.vertical
ID: layout.REGULAR
Group: Layout
This value indicates a regular layout environment for the specified dimension
Related: layoutOverview, layout.horizontal, layout.vertical
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
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).
CurrentOrientation == PORTRAITRelated: CurrentOrientation, PORTRAIT_UPSIDE_DOWN
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).
CurrentOrientation == PORTRAIT_UPSIDE_DOWNRelated: CurrentOrientation, PORTRAIT
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).
CurrentOrientation == LANDSCAPE_LEFTRelated: CurrentOrientation, LANDSCAPE_RIGHT
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).
CurrentOrientation == LANDSCAPE_RIGHTRelated: CurrentOrientation, LANDSCAPE_LEFT
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
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.
showKeyboard()function touched(touch)
--Show keyboard when the screen is touched
showKeyboard()
endRelated: hideKeyboard, isKeyboardShowing, keyboardBuffer
ID: hideKeyboard
Group: Showing and Hiding the Keyboard
This function disables keyboard input and hides the software keyboard if necessary.
hideKeyboard()Related: showKeyboard, isKeyboardShowing, keyboardBuffer
ID: isKeyboardShowing
Group: Showing and Hiding the Keyboard
This function returns whether the keyboard is currently active in the viewer.
isKeyboardShowing()true if the keyboard is showing, false if not
Related: showKeyboard, hideKeyboard, keyboardBuffer
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.
buffer = keyboardBuffer()Contents of keyboard buffer as a string
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
endRelated: showKeyboard, hideKeyboard
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..
BACKSPACEfunction keyboard(key)
-- Did the user press backspace?
if key == BACKSPACE then
-- Do something
end
endRelated: keyboardOverview, showKeyboard
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.
startRecording()Related: stopRecording, isRecording
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.
stopRecording()Related: startRecording, isRecording
ID: isRecording
Group: Recording Video of Your Project
Use this function to programatically determine whether Codea is currently recording the screen.
isRecording()Boolean, whether Codea is recording the screen
Related: startRecording, stopRecording
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
viewer.close()function touched(touch)
--Exit if user taps
if touch.tapCount == 1 and touch.state == ENDED then
viewer.close()
end
endRelated: viewer.mode, FULLSCREEN_NO_BUTTONS
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.
viewer.restart()function touched(touch)
--Restart if user taps
if touch.tapCount == 1 and touch.state == ENDED then
viewer.restart()
end
endRelated: viewer.close
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
local img = viewer.snapshot()image, the contents of the screen
function touched(touch)
-- Capture the screen on tap
if touch.tapCount == 1 and touch.state == ENDED then
snapshot = viewer.snapshot()
end
endRelated: image
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.
viewer.alert( message )
viewer.alert( message, title )message— string, message to displaytitle— string, title of alert view
function touched(touch)
--Show alert if user taps
if touch.tapCount == 1 and touch.state == ENDED then
viewer.alert( "Hello World" )
end
endID: 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.
viewer.share( image )
viewer.share( string )content— image or string, content to share
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
endID: 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
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
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
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
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.
clip( x, y, width, height )
clip() --Disables clippingx— integer, x coordinate of the lower-left corner of the clipping rectangley— integer, y coordinate of the lower-left corner of the clipping rectanglewidth— integer, width of the clipping rectangleheight— integer, height of the clipping rectangle
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.
setContext()
setContext( image )
setContext( image, useDepth )image— image, all drawing operations will occur on this image instead of on screenuseDepth— boolean, whether a depth buffer should be created for this image, defaults to false if not specified
-- 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
endRelated: image
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.
noise( x )
noise( x, y )
noise( x, y, z )x— float, x location of the sampley— float, y location of the samplez— float, z location of the sample
{'description': 'Perlin noise value from -1.0 to 1.0 at the given location.', 'type': 'number'}
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.
background( gray )
background( gray, alpha )
background( red, green, blue )
background( red, green, blue, alpha )
background( color )gray— int from0to255, specifies value between white and blackalpha— int from0to255, specifies opacity of the backgroundred— int from0to255, specifies red amount of the backgroundgreen— int from0to255, specifies green amount of the backgroundblue— int from0to255, specifies blue amount of the backgroundcolor— a value of the color datatype
function draw()
-- Dark blueish background
background(0, 50, 70)
-- Do some drawing
endRelated: color
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.
ellipse( x, y, diameter )
ellipse( x, y, width, height )x— x-coordinate of the ellipsey— y-coordinate of the ellipsewidth— width of the ellipseheight— height of the ellipse
Related: ellipseMode, fill, stroke
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.
rect( x, y, width, height )x— x-coordinate of the lower-left cornery— y-coordinate of the lower-left cornerwidth— width of the rectangleheight— height of the rectangle
Related: rectMode, fill, stroke
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.
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 )asset— asset key of the sprite to use, in the following format:asset.MyFileNameorCAMERAimage— image to draw onto the screenx— x-coordinate of the center of the sprite (this can be changed withspriteMode)y— y-coordinate of the center of the sprite (this can be changed withspriteMode)width— optional width of the sprite in pixelsheight— optional height of the sprite in pixels. Ifwidthis specified andheightis not, thenheightis automatically computed to preserve the aspect ratio of the image.
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
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.
text( string, x, y )string— the text string that you would like to draw onto the screenx— x-coordinate of the center of the text (this can be changed withtextMode)y— y-coordinate of the center of the text (this can be changed withtextMode)
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
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.
line( x1, y1, x2, y2 )x1— x-coordinate of the first pointy1— y-coordinate of the first pointx2— x-coordinate of the second pointy2— y-coordinate of the second point
function draw()
background(128)
stroke(255)
line(10, 10, 80, 80)
endRelated: lineCapMode, stroke, strokeWidth, smooth, noSmooth
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.
image( width, height )
image.width
image.height
image(data)
image(source)source— CAMERA constant, to copy the frame from the current capture sourcewidth— integer, the width of the image in pixelsheight— integer, the height of the image in pixelspremultiplied— 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.
{'description': 'The newly created image of given width and height', 'type': 'image'}
-- 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
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.
image.get( x, y )x— integer, x location of the pixel to queryy— integer, y location of the pixel to query
{'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'}
r,g,b,a = myImage:get( 15, 15 )
r,g,b = myImage:get( 25, 25 )Related: image, image.set
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.
image.set( x, y, color )
image.set( x, y, r, g, b, a)
image.set( x, y, r, g, b)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 tor, g, b, a— integer, the red, green, blue and alpha value to set the pixel to. Between0and255.
myImage:set( 15, 15, color(20,30,40,255) )myImage:set( 15, 15, 20, 30, 40, 255)Related: image, image.set, color
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.
image:copy()
image:copy(x, y, width, height)x— integer, x location of the leftmost pixels of the copy region.y— integer, y location of the topmost pixels of the copy regionwidth— positive integer, width in pixels of the copy regionheight— positive integer, height in pixels of the copy region
{'description': 'The newly created image with a copy of the given image or a subregion of it.', 'type': 'image'}
newImage = myImage:copy()newImage = myImage:copy(20,40,100,100)Related: image, image.set
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.
translate( x, y )
translate( x, y, z )x— amount of horizontal translation, in pixelsy— amount of vertical translation, in pixelsz— amount of depth translation, in pixels
Related: rotate, scale, pushMatrix, popMatrix, resetMatrix
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
asset.FileNamename— string, the name of this file, including its extensionpath— string, the full path to this fileext— string, the file extension for this filetype— the type of this file, can beSPRITES,MODELS,SOUNDS,MUSIC,TEXT,SHADERS
-- 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
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)
asset.FolderNamepath— string, the full path to this foldertype— string, the type of this folder (if it represents a bundle type). Can bePROJECTorSHADERSext— string, the file extension of this folder, will be an empty string unless the folder has a specific extensionall— table, a table with every file and folder in this folder, the table is keyed by file name and the values are eitherassets.key(files) orassets(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 anassetsobject of the folder being monitored
-- 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
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.
rotate( angle )
rotate( angle, x, y, z )angle— amount of rotation in degreesx— float, x value for the axis of rotationy— float, y value for the axis of rotationz— float, z value for the axis of rotation
Related: translate, scale, pushMatrix, popMatrix
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).
scale( amount )
scale( x, y )
scale( x, y, z )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
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().
zLevel( z )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
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.
perspective()
perspective( fov )
perspective( fov, aspect )
perspective( fov, aspect, near, far )fov— float, field of view in degreesaspect— float, aspect ratio of the screen. Defaults to WIDTH/HEIGHTnear— float, near clipping plane, defaults to 0.1far— float, far clipping plane, default value is computed based on the height of the screen
Related: projectionMatrix, ortho, camera, matrix, WIDTH, HEIGHT
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 ).
ortho()
ortho( left, right, bottom, top )
ortho( left, right, bottom, top,
near, far )left— float, left edge of the frustumright— float, right edge of the frustumbottom— float, bottom edge of the frustumtop— float, top edge of the frustum
Related: projectionMatrix, perspective, camera, matrix, WIDTH, HEIGHT
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.
camera( eyeX, eyeY, eyeZ,
centerX, centerY, centerZ,
upX, upY, upZ )eyeX/Y/Z— floats, position of the "eye" in 3DcenterX/Y/Z— floats, coordinate to look atupX/Y/Z— floats, up-vector of the camera, defaults to (0, 1, 0)
Related: viewMatrix, perspective, matrix, WIDTH, HEIGHT
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.
applyMatrix( matrix )matrix— matrix, the transformation to multiply against the current world transform
Related: modelMatrix, matrix, pushMatrix, translate
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.
modelMatrix()
modelMatrix( matrix )matrix— matrix, the transformation to set as the current world transform
{'description': 'The current model matrix when called with no arguments', 'type': 'matrix'}
Related: viewMatrix, projectionMatrix, matrix, pushMatrix
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.
viewMatrix()
viewMatrix( matrix )matrix— matrix, the transformation to set as the current view transform
{'description': 'The current view matrix when called with no arguments', 'type': 'matrix'}
Related: modelMatrix, camera, projectionMatrix, matrix
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.
projectionMatrix()
projectionMatrix( matrix )matrix— matrix, the transformation to set as the current projection transform
{'description': 'The current projection matrix when called with no arguments', 'type': 'matrix'}
Related: modelMatrix, perspective, ortho, viewMatrix, matrix
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().
color.r
color.g
color.b
color.a
myColor = color( 255, 0, 0, 255 ) --redr— int, the red component of this color from0to255g— int, the green component of this color from0to255b— int, the blue component of this color from0to255a— int, the alpha component of this color from0to255
{'description': 'color, a color type with the specified components', 'type': 'color'}
--Fill with red
c = color( 255, 0, 0 )
fill( c )Related: fill, stroke, tint, background
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.
c1 = color( 0, 0, 0, 128 )
c2 = color( 255, 255, 255, 255 )
c3 = c1:blend( c2 )c— color, compute the blending between this color and c
{'description': 'Color computed by blending this color and c', 'type': 'color'}
Related: color, color.mix
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.
c1 = color( 255, 0, 0, 255 )
c2 = color( 0, 255, 0, 255 )
c3 = c1:mix( c2, 0.5 )c— color, compute the mixing between this color and camount— 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.
{'description': 'Color computed by mixing this color and c by amount', 'type': 'color'}
Related: color, color.blend
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).
blendMode()
blendMode( NORMAL | ADDITIVE | MULTIPLY )
blendMode( srcFactor, destFactor )
blendMode( srcFactor, destFactor,
srcAlpha, destAlpha )mode— eitherNORMAL,MULTIPLYorADDITIVE
NORMAL: specifies normal alpha-based blending
MULTIPLY: specifies multiplicative blending
ADDITIVE: specifies additive blending
srcFactor—ZEROONEDST_COLORONE_MINUS_DST_COLORSRC_ALPHAONE_MINUS_SRC_ALPHADST_ALPHAONE_MINUS_DST_ALPHASRC_ALPHA_SATURATEdestFactor—ZEROONESRC_COLORONE_MINUS_SRC_COLORSRC_ALPHAONE_MINUS_SRC_ALPHADST_ALPHAONE_MINUS_DST_ALPHAsrcAlpha— When this parameter is used, the factor specified forsrcAlphawill be used to determine how to calculate the alpha value of the source fragment.destAlpha— When this parameter is used, the factor specified fordestAlphawill be used to determine how to calculate the alpha value of the destination fragment.
{'description': 'The current blend mode if called without arguments (up to four values can be returned). Returns nothing if called with arguments.'}
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
blendEquation()
blendEquation( ADD | SUBTRACT | REVERSE_SUBTRACT | MIN | MAX )
blendEquation( equation )
blendEquation( equation, alphaEquation )equation— Can be eitherADD,SUBTRACT,REVERSE_SUBTRACT,MINorMAX
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
{'description': 'The current blend equation and alpha equation if called without arguments. Returns nothing if called with arguments.'}
Related: blendMode
ID: ellipseMode
Group: Style
Sets the origin of the ellipses drawn with the ellipse() function. The default is ellipseMode( CENTER ).
ellipseMode()
ellipseMode(CENTER|RADIUS|CORNER|CORNERS)mode— eitherCENTER,RADIUS,CORNERorCORNERS
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.
{'description': 'The current ellipse mode if called without arguments. Returns nothing if called with arguments.'}
Related: ellipse
ID: rectMode
Group: Style
Sets the origin of the rectangles drawn with the rect() function. The default is rectMode( CORNER ).
rectMode()
rectMode(CENTER|RADIUS|CORNER|CORNERS)mode— eitherCENTER,RADIUS,CORNERorCORNERS
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.
{'description': 'The current rect mode if called without arguments. Returns nothing if called with arguments.'}
Related: rect
ID: spriteMode
Group: Style
Sets the origin of the sprites drawn with the sprite() function. The default is spriteMode( CENTER ).
spriteMode()
spriteMode( CENTER|RADIUS|CORNER|CORNERS )mode— eitherCENTER,RADIUS,CORNERorCORNERS
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.
{'description': 'The current sprite mode if called without arguments. Returns nothing if called with arguments.'}
Related: sprite
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.
w, h = spriteSize(asset.builtin.Planet_Cute.Character_Boy)
w, h = spriteSize( image )name— asset key for the sprite, e.g.,asset.MyFileNameimage— image object
{'description': 'Width and height of the sprite specified by asset, or image object', 'type': 'integer'}
Related: assetsOverview, sprite, image
ID: textMode
Group: Style
Sets the origin of text drawn with the text() function. The default is textMode( CENTER ).
textMode()
textMode( CENTER|CORNER )mode— eitherCENTERorCORNER
CENTER: x, y specifies the center of the text.
CORNER: x, y specifies the lower left corner of the text.
{'description': 'The current text mode if called without arguments. Returns nothing if called with arguments.'}
Related: text
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.
lineCapMode()
lineCapMode( ROUND | SQUARE | PROJECT )mode— eitherROUND,SQUAREorPROJECT
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
{'description': 'The current line cap mode if called without arguments. Returns nothing if called with arguments.'}
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
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.
fill()
fill( gray )
fill( gray, alpha )
fill( red, green, blue )
fill( red, green, blue, alpha )
fill( color )gray— int from0to255, specifies value between white and blackalpha— int from0to255, specifies opacity of the fillred— int from0to255, specifies red amount of the fillgreen— int from0to255, specifies green amount of the fillblue— int from0to255, specifies blue amount of the fillcolor— a value of the color datatype
{'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
ID: noFill
Group: Style
Sets the color of the fill to completely transparent.
noFill()Related: fill, noStroke
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.
tint()
tint( gray )
tint( gray, alpha )
tint( red, green, blue )
tint( red, green, blue, alpha )
tint( color )gray— int from0to255, specifies value between white and blackalpha— int from0to255, specifies opacity of the tintred— int from0to255, specifies red amount of the tintgreen— int from0to255, specifies green amount of the tintblue— int from0to255, specifies blue amount of the tintcolor— a value of the color datatype
{'description': 'Four values (r,g,b,a) representing the current tint color if called without arguments. Returns nothing if called with arguments.', 'type': 'integer'}
background(127, 127, 127, 255)
tint(255, 0, 0)
sprite(asset.builtin.Planet_Cute.Character_Boy, WIDTH / 2, HEIGHT / 2)Related: sprite, noTint
ID: noTint
Group: Style
Sets the color of the tint to white and completely opaque.
noTint()Related: tint, sprite
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.
stroke()
stroke( gray )
stroke( gray, alpha )
stroke( red, green, blue )
stroke( red, green, blue, alpha )
stroke( color )gray— int from0to255, specifies value between white and blackalpha— int from0to255, specifies opacity of the strokered— int from0to255, specifies red amount of the strokegreen— int from0to255, specifies green amount of the strokeblue— int from0to255, specifies blue amount of the strokecolor— a value of the color datatype
{'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
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.
strokeWidth()
strokeWidth( width )width— int or float, the width in pixels of the stroke
{'description': 'The current stroke width if called without arguments. Returns nothing if called with arguments.', 'type': 'number'}
Related: stroke, noStroke
ID: noStroke
Group: Style
Sets the stroke width to zero.
noStroke()Related: stroke, strokeWidth
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
smooth()Related: noSmooth, line, lineCapMode
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.
noSmooth()Related: smooth, line, lineCapMode
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".
font()
font( name )name— string, the name of the font to use. A list of available fonts can be found by tapping on thefont()function in the code editor.
{'description': 'The current font if called without arguments. Returns nothing if called with arguments.', 'type': 'string'}
Related: text, fontSize
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.
fontSize()
fontSize( size )size— float, the size of the font (in points). Must be greater than 0.0.
{'description': 'The current font size if called without arguments. Returns nothing if called with arguments.', 'type': 'number'}
Related: text, font
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.
fontMetrics(){'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
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 ).
textAlign()
textAlign( LEFT|CENTER|RIGHT )ALIGN— Can beLEFT,CENTERorRIGHT
{'description': 'The current text alignment if called without arguments. Returns nothing if called with arguments.'}
Related: text, textWrapWidth
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.
textWrapWidth()
textWrapWidth( width )width— float, width before the text rendered bytext()word-wraps
{'description': 'The current text wrap width if called without arguments. Returns nothing if called with arguments.', 'type': 'number'}
background(100, 120, 160)
font("Georgia")
fill(255)
fontSize(20)
textWrapWidth(70)
text("Hello World!", WIDTH/2, HEIGHT/2)Related: text, textAlign
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.
width = textSize( string )
width, height = textSize( string )string— string, the string to measure
{'description': 'width and height of the text string when rendered with the current font size and style.', 'type': 'number'}
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
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()
pushMatrix()Related: popMatrix, resetMatrix, translate, rotate, scale
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()
popMatrix()Related: pushMatrix, resetMatrix, translate, rotate, scale
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.
resetMatrix()Related: pushMatrix, popMatrix, translate, rotate, scale
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()
pushStyle()Related: popStyle, resetStyle
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()
popStyle()Related: pushStyle, resetStyle
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()
resetStyle()Related: pushStyle, popStyle
ID: WIDTH
Group: Constants
This constant is set to the width of the screen in pixels.
WIDTH{'description': 'Width of the screen in pixels', 'type': 'integer'}
Related: HEIGHT
ID: HEIGHT
Group: Constants
This constant is set to the height of the screen in pixels.
HEIGHT{'description': 'Height of the screen in pixels', 'type': 'integer'}
Related: WIDTH
ID: ElapsedTime
Group: Variables
Query this variable to get the current elapsed time, in seconds, while running your project.
ElapsedTime{'description': 'Time in seconds since the start of running the project', 'type': 'number'}
Related: DeltaTime
ID: DeltaTime
Group: Variables
Query this variable to get the time elapsed, in seconds, since the last draw call while running your project.
DeltaTime{'description': 'Time in seconds since the start of the previous frame', 'type': 'number'}
Related: ElapsedTime
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.
ContentScaleFactor{'description': 'Content scale factor of the viewer', 'type': 'integer'}
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)
cameraSource( source )
cameraSource()source— EitherCAMERA_FRONTorCAMERA_BACK, determines the source to use.
{'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'}
cameraSource( CAMERA_FRONT )
cameraSource( CAMERA_BACK )
currentSource = cameraSource()Related: image, sprite, spriteSize, CAMERA, CAMERA_DEPTH, CAMERA_FRONT, CAMERA_BACK
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.
CAMERAimg = image(CAMERA)
sprite(CAMERA, x, y)
local m = mesh()
m.texture = CAMERARelated: image, sprite, mesh
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.
CAMERA_DEPTHimg = image(CAMERA_DEPTH)
sprite(CAMERA_DEPTH, x, y)
local m = mesh()
m.texture = CAMERA_DEPTHRelated: image, sprite, mesh
ID: CAMERA_FRONT
Group: Camera Input
Select the front camera of the device for use when using CAMERA.
CAMERA_FRONTRelated: CAMERA, cameraSource
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
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
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
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
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.
for i,v in ipairs( t ) do body end
-- This will iterate over the pairs:
-- (1,t[1]), (2,t[2]), ...table— table to iterate over
Returns three values: an iterator function, the table, and 0
Related: for, pairs
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.
for k,v in pairs( t ) do body end
-- This will iterate over all key-value
-- pairs in table ttable— table to iterate over
Returns three values: the next function, the table t, and nil
Related: for, ipairs
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.
table.concat( table )
table.concat( table, sep )
table.concat( table, sep, i )
table.concat( table, sep, i, j )table— table to concatenatesep— separator stringi— int, starting index to concatenate fromj— int, ending index
A string of the elements in table concatenated with each other, separated by sep
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.
table.move( a1, f, e, t )
table.move( a1, f, e, t, a2 )a1— table to move elements fromf— integer, starting index in table to move frome— integer, ending index in table to move fromt— integer, starting index in table to move intoa2— table to move elements into (defaults toa1)
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.
table.insert( table, value )
table.insert( table, pos, value )table— table to insert intopos— int, position to insetvalue— value to insert
Related: table.remove
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.
table.remove( table )
table.remove( table, pos )table— table to insert intopos— int, position of value to remove
Value of the removed element
Related: table.insert
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.
table.pack( ... )...— arguments to pack into table
table with all parameters packed
Related: table.unpack
ID: table.unpack
Group: Tables
Returns the elements from the given list.
table.unpack( list )list— list to unpack
elements unpacked from list
Related: table.pack
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.
table.sort( table )
table.sort( table, comp )table— the table to sortcomp— a function that receives two table elements and returns true when the first is less than the second
ID: os.clock
Group: Date and Time
Returns an approximation of the amount in seconds of CPU time used by the program.
os.clock()Approximation of the amount in seconds of CPU time used by the program.
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.
os.difftime( t2, t1 )t2— Ending timet1— Starting time
Number of seconds from time t1 to time t2.
Related: os.time
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')).
os.date()
os.date( format )
os.date( format, time )format— String used to format the returned datetime— If the time argument is present, this is the time to be formatted (see the os.time function for a description of this value).
A string or a table containing the date and time.
Related: os.time, os.setlocale
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.
os.setlocale( locale )
os.setlocale( locale, category )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"
When called with nil for the first argument, returns the name of the current locale for the given category.
Related: os.date, os.time
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.
os.time()
os.time( table )table— This table must have fieldsyear,month, andday, and may have fieldshour,min,sec, andisdst
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
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.
string.byte( s )
string.byte( s, i )
string.byte( s, i, j )s— string to usei— first index, defaults to 1j— last index, defaults toi
The internal numerical codes for characters s[i] up to s[j]
Related: string.char
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.
string.char( ... )...— a variable number of numerical codes
String composed of characters equal to the numerical codes used as arguments
Related: string.byte
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).
string.dump( function )
string.dump( function, strip )function— a function to convert to binary stringstrip— boolean, whether to strip debug information
Binary string representation of the specified 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.
string.find( s, pattern )
string.find( s, pattern, init )
string.find( s, pattern, init, plain )s— string to search inpattern— pattern to look forinit— starting character in string to search from, default is 1plain— boolean, perform a plain substring search
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
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.
string.format( formatstring, ... )formatstring— string defining the format
A formatted string
s = string.format("Number is %d", 5)
print( s )
-- prints "Number is 5"ID: string.len
Group: Strings
Receives a string and returns its length. The empty string "" has length 0.
string.len( s )s— get the length of this string
Length of string s
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.
string.gmatch( s, pattern )s— string to searchpattern— pattern to match
Iterator function over matches of pattern within the string
-- 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
endRelated: patterns, string.gsub
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).
string.gsub( s, pattern, repl )
string.gsub( s, pattern, repl, n )s— string to substitutepattern— pattern to matchrepl— string, table or function, replacement parametern— integer, number of occurrences to match (all if not specified)
Returns a copy of s with substitutions made, as well as the number of matches
x = string.gsub("hello world",
"(%w+)", "%1 %1")Related: patterns, string.gmatch
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.
string.lower( s )s— get a lowercase version of this string
Lowercase version of string s
Related: string.upper
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.
string.upper( s )s— get an uppercase version of this string
Uppercase version of string s
Related: string.lower
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.
string.match( s, pattern )
string.match( s, pattern, init )s— string to searchpattern— pattern to matchinit— starting location in string
Captures from the first match of pattern in string s, or nil if none were found
Related: string.find
ID: string.rep
Group: Strings
Returns a string that is the concatenation of n copies of the string s.
string.rep( s, n )s— string to replicaten— int, number of times to replicate the string
n concatenations of string s
ID: string.reverse
Group: Strings
This function returns the string s reversed.
string.reverse( s )s— string to reverse
s reversed
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.
string.sub( s, i )
string.sub( s, i, j )s— find substring of this stringi— int, starting indexj— int, ending index
Substring of string s
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.
string.pack( fmt, v1, v2, ... )fmt— format string specifying binary format...— arguments to pack
Values packed into binary string
Related: string.packsize, string.unpack
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'
string.packsize( fmt )fmt— format string specifying binary format
Size of string packed with the given format
Related: string.pack, string.unpack
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.
string.unpack( fmt, s )
string.unpack( fmt, s, pos )fmt— format string specifying binary formats— string to unpack
The values packed in s
Related: string.pack
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.
ID: math.abs
Group: Math
This function returns the absolute value of value. For example, math.abs(-5) returns 5.
math.abs( value )value— int or float, the number to get the absolute value of
The absolute value of value
ID: math.acos
Group: Math
This function returns the arc cosine of value in radians
math.acos( value )value— int or float, compute the arc cosine of this number
The arc cosine of value in radians
Related: math.asin, math.atan
ID: math.asin
Group: Math
This function returns the arc sine of value in radians
math.asin( value )value— int or float, compute the arc sine of this number
The arc sine of value in radians
Related: math.acos, math.atan
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
math.atan( y )
math.atan( y, x )y— number, numerator for arc tangentx— number, denominator for arc tangent (defaults to 1)
The arc tangent of y/x in radians
Related: math.asin, math.acos
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.
math.ceil( value )value— int or float, compute the smallest integer larger than or equal to this number
The smallest integer larger than or equal to value
Related: math.floor
ID: math.cos
Group: Math
This function returns the cosine of value (assumed to be in radians).
math.cos( value )value— int or float, compute the cosine of this number
Cosine of value
Related: math.sin, math.tan
ID: math.cosh
Group: Math
This function returns hyperbolic cosine of value.
math.cosh( value )value— int or float, compute the hyperbolic cosine of this number
Hyperbolic cosine of value
Related: math.sinh, math.tanh
ID: math.deg
Group: Math
This function returns the angle specified by value (given in radians) in degrees.
math.deg( value )value— int or float, angle in radians to convert to degrees
Angle specified by value (in radians) in degrees
Related: math.rad
ID: math.rad
Group: Math
This function returns the angle specified by value (given in degrees) in radians.
math.rad( value )value— int or float, angle in degrees to convert to radians
Angle specified by value (in degrees) in radians
Related: math.deg
ID: math.exp
Group: Math
This function returns e raised to value
math.exp( value )value— int or float, exponent of e
e raised to the power of value
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.
math.floor( value )value— int or float, compute the largest integer smaller than or equal to this number
The largest integer smaller than or equal to value
Related: math.ceil
ID: math.fmod
Group: Math
This function returns the remainder of the division of x by y that rounds the quotient towards zero.
math.fmod( x, y )x— int or floaty— int or float
The remainder of the division of x by y
Related: math.modf
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).
math.frexp( value )value— int or float
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
ID: math.ldexp
Group: Math
This function returns m2^e (e should be an integer)
math.ldexp( m, e )m— int or floate— int
m2^e
Related: math.frexp
ID: math.log
Group: Math
This function returns the natural logarithm of value
math.log( value )value— int or float, compute the natural logarithm of this value
The natural logarithm of value
Related: math.log10
ID: math.log10
Group: Math
This function returns the base-10 logarithm of value
math.log10( value )value— int or float, compute the base-10 logarithm of this value
The base-10 logarithm of value
Related: math.log
ID: math.max
Group: Math
This function returns maximum value among its arguments.
math.max( value, ... )value— any comparable value
The maximum value among its arguments
Related: math.min
ID: math.min
Group: Math
This function returns minimum value among its arguments.
math.min( value, ... )value— any comparable value
The minimum value among its arguments
Related: math.max
ID: math.modf
Group: Math
This function returns two numbers, the integral part of value and the fractional part of value.
math.modf( value )value— int or float
Two numbers, the integral part of value and the fractional part of value
Related: math.fmod
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].
math.random()
math.random( maximum )
math.random( minimum, maximum )minimum— int, minimum value of returned pseudo-random numbermaximum— int, maximum value of returned pseudo-random number
A uniform pseudo-random real number or integer (depending on parameters)
Related: math.randomseed
ID: math.randomseed
Group: Math
Sets value as the "seed" for the pseudo-random number generator. Equal seeds produce equal sequences of numbers.
math.randomseed( value )value— int, seed of the pseudo-random number generator
A uniform pseudo-random real number or integer (depending on parameters)
Related: math.random
ID: math.sin
Group: Math
This function returns the sine of value (assumed to be in radians).
math.sin( value )value— int or float, compute the sine of this number
Sine of value
Related: math.cos, math.tan
ID: math.sinh
Group: Math
This function returns hyperbolic sine of value.
math.sinh( value )value— int or float, compute the hyperbolic sine of this number
Hyperbolic sine of value
Related: math.cosh, math.tanh
ID: math.tan
Group: Math
This function returns the tangent of value (assumed to be in radians).
math.tan( value )value— int or float, compute the tangent of this number
Tangent of value
Related: math.sin, math.cos
ID: math.tanh
Group: Math
This function returns hyperbolic tangent of value.
math.tanh( value )value— int or float, compute the hyperbolic tangent of this number
Hyperbolic tangent of value
Related: math.sinh, math.cosh
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.
math.sqrt( value )value— int or float, compute the square root of this number
Square root of value
Related: math.pow
ID: math.tointeger
Group: Math
If value is convertible to an integer, returns that integer. Otherwise returns nil.
math.tointeger( value )value— float, value to convert to integer
value converted to an integer, or nil
Related: math.type
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.
math.type( value )value— int or float, get the type of this value
"integer" or "float"
Related: math.tointeger
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.
math.ult( m, n )m— integer, value for mn— integer, value for n
true if m is below integer n when compared as unsigned
ID: math.huge
Group: Math
A value larger than or equal to any other numerical value.
math.hugeA value larger than or equal to any other numerical value
ID: math.pi
Group: Math
The value of pi.
math.piValue of pi
ID: math.maxinteger
Group: Math
Specifies an integer with the maximum value for an integer
math.maxintegerMaximum value for an integer
Related: math.mininteger
ID: math.mininteger
Group: Math
Specifies an integer with the minimum value for an integer
math.minintegerMinimum value for an integer
Related: math.maxinteger
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))
objc.ClassNameAn intermediary type which can be used to access the native class' properties and methods.
-- 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
ID: objc.delegate
Group: Objective-C
Returns a type which can be instantiated and used as an Objective-C delegate for the specified type.
objc.delegate("DelegateName")A type to be used as an Objective-C delegate.
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")
endRelated: objc
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.
objc.class("ClassName")A type to be used as an Objective-C class.
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
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.
objc.selector("SelectorName")An Objective-C selector (or SEL).
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
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.
objc.set({ 1, 2, 3})An Objective-C NSSet.
Related: objc
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.
objc.string("Text")An Objective-C NSString.
Related: objc
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
objc.enum.EnumName.ValueNameA table containing native enumerations and their values.
-- combine UNAuthorizationOptions options
opts =
objc.enum.UNAuthorizationOptions.badge |
objc.enum.UNAuthorizationOptions.sound |
objc.enum.UNAuthorizationOptions.alertRelated: objc
ID: objc.app
Group: Objective-C
The UIApplication's sharedApplication.
objc.appRelated: objc, objc.viewer
ID: objc.viewer
Group: Objective-C
The runtime UIViewController.
objc.viewerRelated: objc, objc.app
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.
objc.info.KeyA table containing the info dictionary keys and values.
-- test if running in an exported project
isStandalone = objc.info.bundleIdentifier ~= "com.twolivesleft.Codify"Related: objc
ID: objc.insets
Group: Objective-C
Create a UIEdgeInsets.
objc.insets( top, left, bottom, right )top— top value of the UIEdgeInsetsleft— left value of the UIEdgeInsetsbottom— bottom value of the UIEdgeInsetsright— right value of the UIEdgeInsets
ID: objc.log
Group: Objective-C
Log a message using NSLog instead of the Codea console.
objc.log( message )message— Message to display
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.
objc.inspect( class )class— Objective-C class to inspect.
-- inspect the SFSpeechRecognizer class
inspect = objc.inspect(objc.SFSpeechRecognizer)
print("Class has " .. #inspect.methods .. " instance methods.")ID: objc.async
Group: Objective-C
Calls the function parameter on the main thread asynchronously.
objc.async( function )function— Parameterless function to run on the main thread.
Related: objc
ID: objc.point
Group: Objective-C
Create a CGPoint.
objc.point( x, y )x— x position of the CGPointy— y position of the CGPoint
ID: objc.rect
Group: Objective-C
Create a CGRect.
objc.rect( x, y, width, height )x— x position of the CGRecty— y position of the CGRectwidth— width of the CGRectheight— height of the CGRect
ID: objc.size
Group: Objective-C
Create a CGSize.
objc.size( width, height )width— width of the CGSizeheight— height of the CGSize
ID: objc.range
Group: Objective-C
Create a NSRange.
objc.range( loc, len )loc— location of the NSRangelen— length of the NSRange
ID: objc.color
Group: Objective-C
Create a CGColor. For UIColor, use the Codea Color type instead.
objc.color( r, g, b, a )r— red value of the CGColorg— green value of the CGColorb— blue value of the CGColora— alpha value of the CGColor
ID: objc.vector
Group: Objective-C
Create a CGVector.
objc.vector( dx, dy )dx— x direction of the CGVectordy— y direction of the CGVector
ID: objc.affineTransform
Group: Objective-C
Create a CGAffineTransform.
objc.affineTransform( a, b, c, d, tx, ty )a— a value of the CGAffineTransformb— b value of the CGAffineTransformc— c value of the CGAffineTransformd— d value of the CGAffineTransformtx— tx value of the CGAffineTransformty— ty value of the CGAffineTransform
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.
-- 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)
endRelated: objc
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.
openURL( url )
openURL( url, internal )url— string, the url to openinternal— boolean, open the url in an internal browser
function touched(touch)
openURL( 'http://twolivesleft.com' )
endfunction touched(touch)
-- Open in-app browser
openURL( 'http://twolivesleft.com', true )
endID: 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
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.
http.request( url, successFunction )
http.request( url, successFunction,
failFunction )
http.request( url, success, fail,
parameterTable )-
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
-- 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
endRelated: httpCallbackOverview, image
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
ID: osc
Group: Open Sound Control (OSC)
This module contains the functions and parameters necessary to configure, send and receive messages via OSC.
port— int, the port used by theosc.sendfunctionhost— string, the host or IP address used by theosc.sendfunctionlisten— 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
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.
local host = osc.start(9000)port— int, the port on which to start the OSC server. Defaults to 9000
string, the host on which the server is running or nil if the server failed to start
function setup()
local host = osc.start(9000)
print("Server running at: ", host)
endRelated: osc.stop, osc.listen, osc, oscOverview, osc.send
ID: osc.stop
Group: Open Sound Control (OSC)
Stops the OSC server.
osc.stop()Related: osc.start
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.
function osc.listen(address, ...)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
endRelated: osc.start, oscOverview
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).
osc.send(address, ...)address— string, the OSC address to send the message to...— varied, any number of integers, strings or numbers to send
-- 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
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.
parameter.number( name )
parameter.number( name, min, max )
parameter.number( name, min, max, initial )
parameter.number( name, min, max, initial, callback )name— string, the parameter function will create a global variable with this namemin— number, specifies the minimum value that your parameter can takemax— number, specifies the maximum value that your parameter can takeinitial— number, specifies the initial, or starting, value of the parametercallback— function, this function will be called whenever the parameter is changed, it will be given the parameter value as an argument
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)
endRelated: parameter.integer, parameter.text, parameter.color, parameter.boolean, parameter.action, parameter.clear
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.
parameter.integer( name )
parameter.integer( name, min, max )
parameter.integer( name, min, max, initial )
parameter.integer( name, min, max, initial, callback )name— string, the parameter.integer function will create a global variable with this namemin— int, specifies the minimum value that your parameter can takemax— int, specifies the maximum value that your parameter can takeinitial— int, specifies the initial, or starting, value of the parametercallback— function, this function will be called whenever the parameter is changed, it will be given the parameter value as an argument
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)
endRelated: parameter.number, parameter.text, parameter.color, parameter.boolean, parameter.action, parameter.clear
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.
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 )name— string, the parameter function will create a global color variable with this namered— int, specifies the initial value of the red component of the colorgreen— int, specifies the initial value of the green component of the colorblue— int, specifies the initial value of the blue component of the colorgray— int, specifies the gray value of the coloralpha— int, specifies the initial value of the alpha component of the colorcallback— function, this function will be called whenever the parameter is changed, it will be given the new color value as an argument
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)
endRelated: color, parameter.integer, parameter.text, parameter.number, parameter.boolean, parameter.action, parameter.clear
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.
parameter.clear()Related: parameter.number, parameter.integer, parameter.color, parameter.action, parameter.boolean, parameter.watch, output.clear
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.
parameter.boolean( name )
parameter.boolean( name, initial )
parameter.boolean( name, initial, callback )
parameter.boolean( name, callback )name— string, the parameter function will create a global variable with this nameinitial— boolean, specifies the initial value of the boolean parametercallback— function, this function will be called whenever the parameter is changed, it will be given the parameter value as an argument
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) )
endRelated: parameter.integer, parameter.text, parameter.color, parameter.number, parameter.action, parameter.clear
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.
parameter.text( name )
parameter.text( name, initial )
parameter.text( name, initial, callback )
parameter.text( name, callback )name— string, the parameter function will create a global variable with this nameinitial— string, specifies the initial value of the text parametercallback— function, this function will be called whenever the parameter is changed, it will be given the parameter value as an argument
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) )
endRelated: parameter.integer, parameter.boolean, parameter.color, parameter.number, parameter.action, parameter.clear
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.
parameter.action( name, callback )name— string, the parameter function will create a global variable with this namecallback— function, this function will be called whenever the parameter is changed, it will be given the parameter value as an argument
function setup()
-- Creates a button to clear the output
parameter.action("Clear Output", output.clear)
endRelated: parameter.integer, parameter.boolean, parameter.color, parameter.number, parameter.text, parameter.clear
ID: output.clear
Group: Clearing the Parameter List
This function clears the output buffer for the print() function.
output.clear()ID: physics.body
Group: Creating Bodies
This type represents a dynamic rigid body.
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) )type— int, the type of the body, can be STATIC, DYNAMIC or KINEMATICshapeType— readonly, the shape type of the body, can be CIRCLE, POLYGON, CHAIN or EDGEradius— float, the radius of the body, only valid for circle shape typespoints— table, a table containing the points that make up the body, only valid for polygon shape typesx— float, the x position of the body in pixelsy— float, the y position of the body in pixelsposition— vec2, the position of the bodyangle— float, the angle of the body in degreesworldCenter— vec2, the center of mass of the body in world spacelocalCenter— vec2, the center of mass of the body in local spacelinearVelocity— vec2, the current linear velocity of the body in pixels per secondangularVelocity— float, the angular velocity of the body in degrees per seconddensity— float, the density of the body in kg/m^2, 1 by default, cannot be negativemass— float, the mass of the body in kg, cannot be negative. If you set this, density will be ignoredinertia— float, the moment of inertia of the body. Cannot be setrestitution— float, the restitution, or 'bouncyness' of the bodyfriction— 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 bodyactive— boolean, set to false to remove from simulationsensor— 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 otherwisesleepingAllowed— boolean, set to false to prevent bodies from sleeping (default: true)bullet— boolean, set to true for fast moving bodies to prevent tunnelinggravityScale— float, controls the influence of gravity on this body, 1 by defaultlinearDamping— 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 lagjoints— table, returns the list of joints connected to this bodyinfo— value, used for storing arbitrary data in this body
-- create a circle with 25px radius
circle = physics.body(CIRCLE, 25)Related: physics.joint
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.
CIRCLEint
Related: physics.body
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.
POLYGONint
Related: physics.body
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.
CHAINint
Related: physics.body
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.
EDGEint
Related: physics.body
ID: DYNAMIC
Group: Creating Bodies
This constant specifies the dynamic body type.Dynamic bodies move under the influence of collisions, forces, joints and gravity.
DYNAMICint
Related: physics.body
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.
STATICint
Related: physics.body
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.
KINEMATICint
Related: physics.body
ID: physics.joint
Group: Attaching Bodies with Joints
This type represents a joint that constrains two rigid bodies together.
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 )type— int, the type of the joint, can be REVOLUTE, DISTANCE, PRISMATIC, WELD or ROPEbodyA— body, the first body attached to this jointbodyB— body, the second body attached to this jointanchorA— vec2, the anchor for the first body in world coordinatesanchorB— vec2, the anchor for the second body in world coordinatesreactionForce— 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 thresholdreactionTorque— 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 thresholdenableLimit— boolean, whether or not the limit for this joint is enabled. Only certain joints, such as REVOLUTE and PRISMATIC have limitslowerLimit— 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 limitupperLimit— 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 limitenableMotor— boolean, whether or not the motor for this joint is enabled. Only certain joints, such as REVOLUTE and PRISMATIC have motorsmotorSpeed— 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 secondmaxMotorTorque— float, the maximum amount of torque the motor can apply to reach the desired motor speed. Only REVOLUTE joints have this propertymaxMotorForce— float, the maximum amount of force the motor can apply to reach the desired motor speed. Only PRISMATIC joints have this propertylength— float, the length of the joint. Only applies to DISTANCE jointsfrequency— float, The softness of the joint, set to zero for stiff joints. Only applies to DISTANCE and WELD jointsdampingRatio— float, Controls the damping of soft joints, higher values reduce oscillation, set to zero for stiff joints. Only applies to DISTANCE and WELD jointsmaxLength— float, Controls the maximum length (distance between anchor points) of the joint. Only applies to ROPE joints
Related: physics.body
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.
REVOLUTEint
Related: physics.joint
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.
DISTANCEint
Related: physics.joint
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.
PRISMATICint
Related: physics.joint
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.
WELDint
Related: physics.joint
ID: ROPE
Group: Attaching Bodies with Joints
This constant specifies the rope joint type. Rope joints constrain the maximum distance between two bodies.
ROPEint
Related: physics.joint
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
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.
id— number, a unique id that represents this contactstate— int, the current state of this contact, can be BEGAN, CHANGED, ENDEDtouching— 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 contactnormal— vec2, the current normal of this contactnormalImpulse— float, the magnitude of energy used to separate the two colliding bodies projected along the normal vector. Useful for measuring the strength of an impacttangentImpulse— 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 impactpointCount— int, the number of points in the contact manifoldpoints— table, an array of vec2's describing the contact manifoldbodyA— body, the first body in the collision represented by this contactbodyB— body, the second body in the collision represented by this contact
function collide(contact)
if contact.state == BEGAN then
print("HIT!")
end
endRelated: physics.body, physics.joint
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.
myBody:applyForce( force )
myBody:applyForce( force, worldPoint )force— vec2, the amount of force to apply as a vectorworldPoint— vec2, the point to apply the force from, in world coordinates
Related: physics.body, body.applyTorque
ID: body.applyTorque
Group: Creating Bodies
Applies torque to this body object.
myBody:applyTorque( applyTorque )torque— float, the amount of torque
Related: physics.body, body.applyForce
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.
myBody:applyLinearImpulse( impulse )
myBody:applyLinearImpulse( impulse, worldPoint )impulse— vec2, the impulse to apply as a vectorworldPoint— vec2, the point to apply the impulse from, in world coordinates
Related: physics.body, body.applyAngularImpulse
ID: body.applyAngularImpulse
Group: Creating Bodies
Applies an angular impulse to this body object.
myBody:applyAngularImpulse( impulse )impulse— float, the angular impulse
Related: physics.body, body.applyLinearImpulse
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.
myBody:destroy()-- destroy should be used before
-- setting a body to nil
circle = physics.body(CIRCLE, 100)
circle:destroy()
circle = nilRelated: physics.body, body.applyForce, body.destroy
ID: body.testPoint
Group: Creating Bodies
Tests if worldPoint is inside this body.
myBody:testPoint( worldPoint )worldPoint— vec2, the point to test for intersection, in world space
true if worldPoint is inside this body, false otherwise
-- 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!")
endRelated: physics.body, body.applyForce, body.destroy, body.testPoint
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.
myBody:testOverlap( otherBody )otherBody— body, the body to test for intersection with
true if this body is intersecting with otherBody, false otherwise
-- test if two bodies overlap
circle1 = physics.body(CIRCLE, 100)
circle2 = physics.body(CIRCLE, 10)
if circle1:testOverlap(circle2) then
print("HIT!")
endRelated: physics.body, body.applyForce, body.destroy, body.testPoint
ID: body.getLocalPoint
Group: Creating Bodies
Converts a point to the local coordinate space of this body
myBody:getLocalPoint( worldPoint )vec2, coordinate in local space of this body
Related: physics.body, body.applyForce, body.destroy, body.testPoint
ID: body.getWorldPoint
Group: Creating Bodies
Converts a point from the local coordinate space of this body to world space
myBody:getWorldPoint( localPoint )vec2, coordinate in world space
Related: physics.body, body.applyForce, body.destroy, body.testPoint
ID: body.getLinearVelocityFromWorldPoint
Group: Creating Bodies
Samples the linear velocity of this body at a given point in world space.
myBody:getLinearVelocityFromWorldPoint( worldPoint )vec2, linear velocity at worldPoint of this body
Related: physics.body, body.applyForce, body.destroy, body.testPoint
ID: body.getLinearVelocityFromLocalPoint
Group: Creating Bodies
Samples the linear velocity of this body at a given point in local space.
myBody:getLinearVelocityFromLocalPoint( worldPoint )vec2, linear velocity at localPoint of this body
Related: physics.body, body.applyForce, body.destroy, body.testPoint
ID: physics.pause
Group: Physics Simulation Functions
Pauses the physics simulation.
-- pause physics
physics.pause()Related: physics.resume
ID: physics.resume
Group: Physics Simulation Functions
Resumes the physics simulation.
-- resume physics
physics.resume()Related: physics.pause
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.
physics.raycast(start, end)
physics.raycast(start, end, category1)
physics.raycast(start, end, category1,
category2)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
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
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.
physics.raycastAll(start, end)
physics.raycastAll(start, end, category1)
physics.raycastAll(start, end, category1,
category2)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
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
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.
physics.queryAABB(lowerLeft, upperRight)
physics.queryAABB(lowerLeft, upperRight,
category1)
physics.queryAABB(lowerLeft, upperRight,
category1, category2)lowerLeft— vec2, the position of the lower left corner of the query axis-aligned bounding boxupperRight— vec2, the position of the upper right corner of the query axis-aligned bounding box
array, returns all bodies that lie within the supplied bounding box
Related: physics.raycast, physics.raycastAll, physics.queryAABB
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.
physics.gravity()
physics.gravity( x, y )
physics.gravity( grav )
physics.gravity( Gravity )x— float, gravity in the x-axisy— float, gravity in the y-axisgrav— vec2, gravity in both axesGravity— vec3, device gravity used as a special case
vec2, the current world gravity if no parameters are supplied
Related: physics.iterations, physics.pixelToMeterRatio
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.
physics.iterations( velocityIterations,
positionIterations )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
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.
physics.timeStep()
physics.timeStep( timeStep )timeStep— float, time step in seconds
float, the current time step if no parameters are supplied
Related: physics.iterations
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.
ratio = physics.pixelToMeterRatio
physics.pixelToMeterRatio = ratioint, the current ratio
Related: physics.gravity, physics.iterations
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.
physics.continuous = truebool, whether continous collision is set
Related: physics.body
ID: physics.bodies
Group: Creating Bodies
Gets a read-only list of all active bodies.
bodies = physics.bodies-- destroy all static bodies
for i, b in ipairs(physics.bodies) do
if b.type == STATIC then
b:destroy()
end
endRelated: physics.body
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.
-- 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
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 ..."
-- 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
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.
m = mesh()vertices— table, an array of vec2 or vec3 objectscolors— table, an array of color objects. If not set the global fill color is used for all verticestexCoords— table, an array of vec2 objects. If not set, triangles are drawn with color onlytexture— string, image or CAMERA, the texture to use when drawing this mesh. If not set, triangles are drawn with color onlynormals— table, an array of vec3 objects. Not used by mesh, but may be used by custom shaders.shader— shader, a shader objectvalid— bool, true if this mesh is valid for drawingsize— int, number of vertices in this mesh
The newly created empty mesh
-- 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
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.
myMesh:draw()
myMesh:draw(count)count— integer, number of instances of this mesh to draw
Related: mesh
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).
myMesh:setColors( c )
myMesh:setColors( r, g, b )
myMesh:setColors( r, g, b, a )c— color, set all mesh vertices to this colorr— value of the red color component to apply to all verticesg— value of the green color component to apply to all verticesb— value of the blue color component to apply to all verticesa— value of the alpha component to apply to all vertices
Related: mesh
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.
myMesh:clear()Related: mesh
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
myMesh:addRect( x, y, w, h)
myMesh:addRect( x, y, w, h, r)x— float, the x coordinate used to place the rectangley— float, the y coordinate used to place the rectanglew— float, the width of the rectangleh— float, the height of the rectangler— float, the rotation of the rectangle
Returns the index of this rectangle, which can be used to set its position later
Related: mesh, mesh.setRect
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
myMesh:setRect( i, x, y, w, h)
myMesh:setRect( i, x, y, w, h, r)i— int, the index of the rectangle in themeshx— float, the x coordinate used to place the rectangley— float, the y coordinate used to place the rectanglew— float, the width of the rectangleh— float, the height of the rectangler— float, the rotation of the rectangle
Related: mesh, mesh.addRect, mesh.setRectTex, mesh.setRectColor
ID: mesh.setRectTex
Group: Meshes
This method sets the texture coordinates of an existing rectangle with index i.
myMesh:setRectTex( i, s, t, w, h)i— int, the index of the rectangle in themeshs— float, the left edge of the texture rectanglet— float, the bottom edge of the texture rectanglew— float, the width of the texture rectangleh— float, the height of the texture rectangle
Related: mesh, mesh.addRect, mesh.setRect, mesh.setRectColor
ID: mesh.setRectColor
Group: Meshes
This method sets the color of an existing rectangle with index i.
myMesh:setRectColor( i, c)
myMesh:setRectColor( i, r, g, b)
myMesh:setRectColor( i, r, g, b, a)i— int, the index of the rectangle in themeshc— color, the color to set the rectangle tor— int, the red component of the color to useg— int, the green component of the color to useb— int, the blue component of the color to usea— int, the alpha component of the color to use
Related: mesh, mesh.addRect, mesh.setRect, mesh.setRectTex
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.
v = myMesh:vertex( i )
myMesh:vertex( i, x, y, z )
myMesh:vertex( i, vec3 )
myMesh:vertex( i, x, y )
myMesh:vertex( i, vec2 )i— int, the index of the vertex in themeshx— float, the x position to set vertex i toy— float, the y position to set vertex i toz— float, the z position to set vertex i tovec3— vec3, the 3D position to set vertex i tovec2— vec2, the 2D position to set vertex i to
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
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.
t = myMesh:texCoord( i )
myMesh:texCoord( i, x, y )
myMesh:texCoord( i, vec2 )i— int, the index of the texture coordinate in themeshx— float, the x value to set vertex i's texture coordinate toy— float, the y value to set vertex i's texture coordinate tovec2— vec2, the texture coordinate value to set on vertex i
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
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.
c = myMesh:color( i )
myMesh:color( i, r, g, b )
myMesh:color( i, r, g, b, a )
myMesh:color( i, color )i— int, the index of the color in themeshr— 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
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
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.
n = myMesh:normal( i )
myMesh:normal( i, x, y, z )
myMesh:normal( i, vec3 )i— int, the index of the vertex in themeshx— float, the x magnitude of the normal for vertex iy— float, the y magnitude of the normal for vertex iz— float, the z magnitude of the normal for vertex ivec3— vec3, the normal to set vertex i to
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
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.
myMesh:resize(30)size— int, the number of elements in the mesh
Related: mesh, buffer.resize, meshOverview, mesh.clear
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.
b = myMesh:buffer("position")
b = myMesh:buffer("texCoord")
b = myMesh:buffer("color")
b = myMesh:buffer("normal")name— string, either "position", "texCoord", "color" or "normal" or an attribute name declared in an attached shader
A buffer object allowing direct access to an array of mesh data of a particular type
Related: mesh, buffer, shader
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.
b = myMesh:buffer("position")
b = myMesh:buffer("texCoord")
b = myMesh:buffer("color")
b = myMesh:buffer("normal")
b = myMesh:buffer("myAttrib")
b.instanced = trueinstanced— boolean, indicates whether this buffer should be treated as an instanced buffer. Defaults tofalse.
The newly created empty buffer
-- 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 drawnRelated: mesh, meshOverview, buffer.resize
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.
myBuffer:resize(30)size— int, the number of elements in the buffer
Related: buffer, meshOverview, mesh.buffer, mesh.resize
ID: buffer.clear
Group: Buffers
This method clears all data from the buffer and sets its size to 0.
myBuffer:clear()Related: buffer.resize, buffer
ID: buffer.get
Group: Buffers
This method returns a copy of the data in buffer as a Lua table.
myTable = myBuffer:get()A table containing the data in buffer
Related: buffer.set, buffer
ID: buffer.set
Group: Buffers
This method sets the content of buffer to the data contained in table.
myBuffer:set( myTable )table— table, a table of vec2, vec3, vec4 or color
Related: buffer.get, buffer
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.
s = shader()
s = shader(asset.documents.MyShader)
s = shader(vertexProgram,
fragmentProgram)vertexProgram— string, a string defining the vertex program of the shaderfragmentProgram— string, a string defining the fragment program of the shader
A newly created shader
-- Create a shader
myShader = shader(asset.documents.MyShader)
-- Assign it to a mesh
myMesh.shader = myShaderRelated: shaderOverview, mesh, meshOverview, mesh.buffer
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.
triangleVertices = triangulate( points )points— table, an array of vec2 objects representing a polygon
A triangle list generated from the supplied polygon in the form { t1p1, t1p2, t1p3, t2p1, t2p2, t2p3, ..., tNp3 }
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
music( asset )
music( asset, loop )
music( asset, loop, volume )
music( asset, loop, volume, pan )asset— asset key, the asset key of the music track to playloop— boolean, specifies whether this track should continue playing in a loopvolume— number, the initial volume of playback from 0.0 to 1.0pan— number, the stereo panning of playback, from -1.0 to 1.0
-- 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
endRelated: sound
ID: music.volume
Group: Music
This variable controls the currently playing music track's volume. It ranges from 0.0 to 1.0.
-- Getting
vol = music.volume
-- Setting
music.volume = 0.5Volume of the currently playing music track
Related: music
ID: music.pan
Group: Music
This variable controls the currently playing music track's stereo panning. It ranges from -1.0 to 1.0.
-- Getting
pan = music.pan
-- Setting
music.pan = -1.0Panning amount of the currently playing music track
Related: music
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).
-- Getting
time = music.currentTime
-- Setting
music.currentTime = music.duration * 0.5Current time into the playing music track
Related: music.duration, music
ID: music.paused
Group: Music
This variable sets the paused state of the current music track.
-- Getting
isPaused = music.paused
-- Setting
music.paused = truePaused state of the currently music track.
Related: music
ID: music.muted
Group: Music
This variable controls whether the music track is currently muted.
-- Getting
muted = music.muted
-- Setting
music.muted = trueWhether the current track is muted
Related: music
ID: music.duration
Group: Music
Read only. This variable returns the length of the current music track in seconds.
duration = music.durationLength of the current music track in seconds.
Related: music.currentTime, music
ID: music.channels
Group: Music
Read only. This variable returns the number of channels supported by the current track (usually 1 or 2).
channels = music.channelsNumber of channels supported by the current track.
Related: music
ID: music.name
Group: Music
Read only. This value returns the asset string of the currently playing music.
print( music.name )Asset string of current music track
Related: music
ID: music.stop
Group: Music
Stops the currently playing music track.
music.stop()Related: music
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
-- 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 )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 typebuffer— soundbuffer, specifies the raw sound data to playparameterTable— 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
-- 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
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.
soundbuffer( data, format, freq )data— string, uncompressed audio dataformat—FORMAT_MONO8,FORMAT_MONO16,FORMAT_STEREO8orFORMAT_STEREO16freq— integer, the frequency of the data
A new soundbuffer object
-- 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
endRelated: sound
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.
soundBufferSize( size )
soundBufferSize()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.
If no parameters are given, a pair of values: maxBufferSize, currentBufferSize
-- 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
ID: soundsource
Group: Sounds
Created when calling the sound command, represents a live sound currently playing. Can be controlled to alter the playing sound
source = sound(foo)volume— number, the current volume of the sound sourcepitch— number, the current pitch of the sound sourcepan— 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 playbackpaused— boolean, whether the sound source is currently pausedmuted— boolean, whether the sound source is currently muted
Related: sound
ID: soundsource.stop
Group: Sounds
Stops the sound if it is currently playing
soundsource.stop()Related: soundsource
ID: soundsource.rewind
Group: Sounds
Start the sound again from the beginning next time it is played
soundsource.rewind()Related: soundsource
ID: soundsource.fadeTo
Group: Sounds
Fades the volume of the soundsource to the specified volume over the time specified by duration
soundsource.fadeTo(volume, duration)volume— number, volume to fade to, between 0 and 1duration— number, seconds over which to fade volume
Related: soundsource
ID: soundsource.stopFade
Group: Sounds
Cancels the current fading action, if possible
soundsource.stopFade()Related: soundsource
ID: soundsource.pitchTo
Group: Sounds
Adjustes the pitch of the soundsource to the specified pitch over the time specified by duration
soundsource.pitchTo(pitch, duration)pitch— number, pitch to fade toduration— number, seconds over which to adjust pitch
Related: soundsource
ID: soundsource.stopPitch
Group: Sounds
Cancels the current pitch change action, if possible
soundsource.stopPitch()Related: soundsource
ID: soundsource.panTo
Group: Sounds
Adjustes the pan of the soundsource to pan over the time specified by duration
soundsource.panTo(pan, duration)pitch— number, pan to fade to (-1 left, +1 right, 0 center)duration— number, seconds over which to pan the sound
Related: soundsource
ID: soundsource.stopPan
Group: Sounds
Cancels the current pan change action, if possible
soundsource.stopPan()Related: soundsource
ID: soundsource.stopActions
Group: Sounds
Cancels all active actions on the soundsource, if possible
soundsource.stopActions()Related: soundsource
ID: SOUND_JUMP
Group: Sounds
This constant specifies a jump sound. Similar to a character jumping in a platform game.
SOUND_JUMPThe string "jump"
Related: sound
ID: SOUND_HIT
Group: Sounds
This constant specifies a hit sound. For example, when the enemy collides with the player.
SOUND_HITThe string "hit"
Related: sound
ID: SOUND_PICKUP
Group: Sounds
This constant specifies a pickup sound. For example, collecting coins in a game.
SOUND_PICKUPThe string "pickup"
Related: sound
ID: SOUND_POWERUP
Group: Sounds
This constant specifies a powerup sound. For example, collecting bonuses in a game.
SOUND_POWERUPThe string "powerup"
Related: sound
ID: SOUND_SHOOT
Group: Sounds
This constant specifies a shooting sound. For example, firing a bullet in a game.
SOUND_SHOOTThe string "shoot"
Related: sound
ID: SOUND_EXPLODE
Group: Sounds
This constant specifies an explosion sound. For example, a space ship blowing up.
SOUND_EXPLODEThe string "explode"
Related: sound
ID: SOUND_BLIT
Group: Sounds
This constant specifies a generic "blit" sound.
SOUND_BLITThe string "blit"
Related: sound
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.
SOUND_RANDOMThe string "random"
Related: sound
ID: SOUND_NOISE
Group: Sounds
This specifices to use a white noise function as the waveform for this sound
SOUND_NOISEThe integer 3
Related: sound
ID: SOUND_SAWTOOTH
Group: Sounds
This specifices to use a sawtooth function as the waveform for this sound
SOUND_SAWTOOTHThe integer 1
Related: sound
ID: SOUND_SINEWAVE
Group: Sounds
This specifices to use a sine wave function as the waveform for this sound
SOUND_SINEWAVEThe integer 2
Related: sound
ID: SOUND_SQUAREWAVE
Group: Sounds
This specifices to use a square wave function as the waveform for this sound
SOUND_SQUAREWAVEThe integer 0
Related: sound
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.
speech( string )
speech.pitch
speech.volume
speech.rate
speech.preDelay
speech.postDelaystring— string, the utterance to be spokenpitch— 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 utterancepostDelay— float, the amount of time to wait after speaking this utterancevolume— float, a value between 0.0 and 1.0 (default is 1.0)voices— table, an array of availablevoiceobjectsvoice— voice, the default voice to use for speech, usenilfor defaultlanguage— string, the language string representing the voice you wish to use
The newly created utterance to be used with speech.say
-- 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
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.
speech.say( string )
speech.say( utterance )string— string, a string to speak
-- 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
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.
speech.pause()
speech.pause( immediate )immediate— boolean, whether to pause immediately or after the next word
-- Just speak some words immediately
speech.say("Hello world!")
-- Pause it
speech.pause()
-- Later, continue
speech.continue()Related: speech.continue, speech.stop, speech.say
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.
speech.stop()
speech.stop( immediate )immediate— boolean, whether to stop immediately or after the next word
-- Just speak some words immediately
speech.say("Hello world!")
-- Stop it immediately
speech.stop( true )Related: speech.continue, speech.pause, speech.say
ID: speech.continue
Group: Speech
Use this function to resume speech which has been paused with speech.pause
speech.continue()Related: speech.pause, speech.say
ID: speech.speaking
Group: Speech
Check this value to see if the speech synthesizer is currently speaking.
speech.speakingBoolean value indicating whether the system is currently speaking
Related: speech.say
ID: speech.paused
Group: Speech
Check this value to see if the speech synthesizer is currently paused.
speech.pausedBoolean value indicating whether the system is currently paused
Related: speech.say
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.
speech.pitch = 2.0float value, the current global speech pitch
Related: speech
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.
speech.rate = 0.1float value, the current global speech rate
Related: speech
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.
speech.preDelay = 0.0float value, the delay in seconds prior to playing speech
Related: speech
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.
speech.postDelay = 0.0float value, the delay in seconds after playing speech
Related: speech
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.
speech.volume = 1.0float value, the volume of speech
Related: speech
ID: mic.start
Group: Microphone
Use this function to start tracking input from the device microphone
mic.start()Related: mic.stop
ID: mic.stop
Group: Microphone
Use this function to stop tracking input from the device microphone
mic.stop()Related: mic.start
ID: mic.amplitude
Group: Microphone
Sample this value to determine the volume of sound coming into the microphone
local amp = mic.amplitudeRelated: mic.frequency
ID: mic.frequency
Group: Microphone
Sample this value to determine the pitch of sound coming into the microphone
local freq = mic.frequencyRelated: mic.amplitude
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.
pasteboard.copy( text )
pasteboard.copy( image )text— string, text to be copied to the pasteboardimage— image, image data to be copied to the pasteboard, such as image data returned byreadImageor theimage()function
-- Copy some text to the pasteboard
pasteboard.copy( "Some text" )
-- Read the text back out
print( pasteboard.text )Related: pasteboard.text, pasteboard.image
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 ).
text = pasteboard.textText currently on the system pasteboard, nil if there is none.
-- 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
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 ).
img = pasteboard.imageImage currently on the system pasteboard, nil if there is none.
-- 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 = imgRelated: pasteboard.copy, pasteboard.text
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.
readImage( asset )
readImage( asset, width )
readImage( asset, width, height )
readImage( asset, width, height, page )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, usespriteSize.
The image associated with asset or nil if asset doesn't exist or is invalid.
-- Read a sprite into an image
myImage = readImage(asset.builtin.Planet_Cute.Heart)Related: saveImage, image, assetList, assetsOverview
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.
saveImage( asset, image )asset— asset, asset key for the file to save (e.g.,asset .. "MyFile.png")image— image, the image to be saved under asset
-- 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)
endRelated: readImage, image, assetList
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.
readText( asset )asset— asset, asset key to text file (e.g., asset.documents.Readme)
The text content of asset or nil if asset does not exist or is invalid.
-- Read a text file into a string
myString = readText(asset.documents.MyFile)Related: saveText
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.
saveText( asset, text )asset— asset, asset key for the file to save (e.g.,asset .. "MyFile.txt")text— string, the text contents to be saved under asset
-- Save some text content into documents
function setup()
myContent = "Hello World"
saveText(asset.documents .. "Hello.txt", myContent)
endRelated: readText
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.
file.copy( source, destination )source— asset key or asset library, source file or folder to copydestination— asset key or asset library, destination path or folder
Two values: success (boolean) and error message (string or nil). On success: true, nil. On failure: false, "error message".
-- 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
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.
file.move( source, destination )source— asset key or asset library, source file or folder to movedestination— asset key or asset library, destination path or folder
Two values: success (boolean) and error message (string or nil). On success: true, nil. On failure: false, "error message".
-- 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
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.
file.remove( asset )asset— asset key or asset library, file or folder to remove
Two values: success (boolean) and error message (string or nil). On success: true, nil. On failure: false, "error message".
-- 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
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.
file.mkdir( asset )asset— asset key or asset library, path where the directory should be created
Two values: success (boolean) and error message (string or nil). On success: true, nil. On failure: false, "error message".
-- 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
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.
file.rename( asset, newName )asset— asset key, source file or folder to renamenewName— string, the new name for the file or folder
Two values: success (boolean) and error message (string or nil). On success: true, nil. On failure: false, "error message".
-- 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
ID: file.exists
Group: File Operations
This function checks if a file or folder exists at the given path. Returns a boolean value.
file.exists( asset )asset— asset key or asset library, path to check for existence
boolean, true if the path exists, false otherwise
-- 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")
endRelated: file.copy, file.move, file.remove, file.mkdir, file.rename
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.
json.encode( object )
json.encode( object, state )object— table or other object to encode into JSON stringstate— 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.
string value for object encoded as JSON string (or a boolean indicating success if a custom buffer was specified)
-- 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
ID: json.decode
Group: JSON
This function decodes a JSON encoded string into an object (usually a table).
json.decode( string )
json.decode( string, position )
json.decode( string, position, null )string— string to decodeposition— 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
an object represented by the decoded string JSON string
-- 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)
endRelated: json.encode
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.
readLocalData( key )
readLocalData( key, defaultValue )key— string, name of the piece of data you would like to getdefaultValue— if the key doesn't exist, this value is returned instead
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.
-- Load high score
-- Defaults to 0 if it doesnt exist
highscore = readLocalData("highscore", 0)Related: saveLocalData, clearLocalData
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.
saveLocalData( key, value )key— string, name of the piece of data you would like to storevalue— the value to store under key
-- Save high score
saveLocalData("highscore", currentScore)Related: readLocalData, clearLocalData
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.
listLocalData( )A table containing all the keys stored in local data
Related: readLocalData, saveLocalData, clearLocalData
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.
clearLocalData( )Related: readLocalData, saveLocalData
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.
readProjectData( key )
readProjectData( key, defaultValue )key— string, name of the piece of data you would like to getdefaultValue— if the key doesn't exist, this value is returned instead
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
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.
saveProjectData( key, value )key— string, name of the piece of data you would like to storevalue— the value to store under key
Related: readProjectData, clearProjectData
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.
saveProjectInfo( key, value )key— string, name of the project metadata to store. Currently supports "Description" and "Author"value— the value to store under key
Related: readProjectInfo
ID: readProjectInfo
Group: Project Storage
This function reads a value associated with key from the project metadata for the current project.
readProjectInfo( key )key— string, name of the piece of metadata you would like to get
The value associated with key, or nil if the key does not exist
Related: saveProjectInfo
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.
listProjectData( )A table containing all the keys stored in project data
Related: readProjectData, saveProjectData, clearProjectData
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.
clearProjectData( )Related: readProjectData, saveProjectData
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.
readGlobalData( key )
readGlobalData( key, defaultValue )key— string, name of the piece of data you would like to getdefaultValue— if the key doesn't exist, this value is returned instead
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
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.
saveGlobalData( key, value )key— string, name of the piece of data you would like to storevalue— the value to store under key
Related: readGlobalData
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.
listGlobalData( )A table containing all the keys stored in global data
Related: readGlobalData, saveGlobalData
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.
readProjectTab( key )key— string, a key specifying the project and tab you would like to read
A string containing the contents of the tab specified by key. If key is not found, returns nothing.
-- 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
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.
saveProjectTab( key, value )key— string, a key specifying a project and tabvalue— string, the contents to write into the tab specified bykey, a value ofnildeletes the tab.
-- 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
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.
listProjectTabs( )
listProjectTabs( project )project— string, the name of a project to retrieve tabs from
A table containing all the tabs in the specified project
Related: readProjectTab, saveProjectTab
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".
createProject( key )key— string, a key specifying the project you would like to create
-- 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
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".
deleteProject( key )key— string, a key specifying the project you would like to delete
-- Delete a project
deleteProject("Examples:Anagrams")Related: createProject, hasProject, listProjects
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".
hasProject( key )key— string, a key specifying the project you would like to query
true if the specified project exists, false otherwise
-- Check if an example exists
print(hasProject("Examples:Anagrams"))Related: createProject, deleteProject, listProjects
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".
listProjects( )
listProjects( collection )collection— string, the name of the collection to retrieve projects from
A table containing all the projects in the specified collection, or all projects in all collections if none specified
Related: createProject, hasProject, deleteProject
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.
CurrentTouchfunction draw()
background( 0 )
fill( 255, 0, 0 )
ellipse( CurrentTouch.x, CurrentTouch.y, 300 )
endRelated: touch
ID: touch
Group: Handling Touches
This type represents data about a single touch on the screen
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.timestampid— int, a unique identifier for this touchpos— vec2, specifies the position of the touch on the screenprevPos— vec2, specifies the position, from the previous frame, of the touch on the screenprecisePos— 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 movedforce— float, when available, specifies the force of the touchmaxForce— float, when available, specifies the maximum possible force of a touchaltitude— float, stylus only, angle in radians of the stylus with the surface of the screen. A value of0indicates the stylus is parallel to the screen, a value of Pi/2 indicates a stylus perpendicular to the screenazimuth— float, stylus only, angle in radians of the direction in which the stylus is pointingazimuthVec— vec2, stylus only, a unit vector which points in the direction of the stylustype— the type of the touch, can be DIRECT, INDIRECT, STYLUS or POINTERstate— the state of the touch, can be BEGAN, CHANGED, ENDED or CANCELLEDtapCount— how many times the touch has been tappedtimestamp— the time when the touch occurred or when it was last updated
Related: touched, CurrentTouch
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)
function touched(touch)gesture— the gesture object containing information about this event
Related: touch, CurrentTouch
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
gesture.state
gesture.location
gesture.translation
gesture.delta
gesture.pinchScale
gesture.pinchVelocity
gesture.alt
gesture.control
gesture.command
gesture.shift
gesture.capsLockstate— the state of the gesture, can be BEGAN, CHANGED or ENDEDlocation— vec2, the location of the gesture over the viewertranslation— vec2, scroll gestures only. The total amount of 2D translation since the gesture begandelta— vec2, scroll gestures only. The amount of 2D translation since the last timescrollwas calledpinchScale— number, pinch gestures only. The scale of the pinch relative to the two touches since the gesture beganpinchVelocity— number, pinch gestures only. The velocity of the change in pinch scale in scale factor per secondalt— bool, true if the alt (alternate / option) modifier key was held downcontrol— bool, true if the control modifier key was held downcommand— bool, true if the command modifier key was held downshift— bool, true if the shift modifier key was held downcapsLock— bool, true if the caps lock key was held down
Related: hover, scroll, pinch, vec2, BEGAN, CHANGED, ENDED
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
function hover(gesture)gesture— the gesture object containing information about this event
Related: gesture, scroll, pinch, vec2
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
function scroll(gesture)gesture— the gesture object containing information about this event
Related: gesture, hover, pinch, vec2
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
function pinch(gesture)gesture— the gesture object containing information about this event
Related: gesture, hover, scroll, vec2
ID: BEGAN
Group: Touch States
This state occurs when a touch or gesture first begins
BEGANRelated: touch
ID: CHANGED
Group: Touch States
This state occurs when a touch or gesture changes position
CHANGEDRelated: touch
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)
ENDEDRelated: touch
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.
CANCELLEDRelated: touch, ENDED
ID: DIRECT
Group: Touch Types
Direct touches occur when the user's finger touches the screen
DIRECTRelated: touch
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
INDIRECTRelated: touch
ID: STYLUS
Group: Touch Types
A stylus touch occurs when a stylus interacts with the device's screen
STYLUSRelated: touch
ID: POINTER
Group: Touch Types
A pointer touch occurs when using an indirect input device such as a trackpad or mouse
POINTERRelated: touch
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.
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 )x— number, the x component of this vec2y— number, the y component of this vec2
--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
ID: vec2.dot
Group: 2D Vector
This method returns the scalar dot product between two vec2 types
v1 = vec2( 1, 1 )
x = v1:dot( v )vector— vec2, compute the dot product with this vector
number, dot product between this vec2 and vector
Related: vec2
ID: vec2.normalize
Group: 2D Vector
This method returns a normalized version of the vector
v1 = vec2( 5, 5 )
v1 = v1:normalize()vec2, normalized version of this vec2
Related: vec2
ID: vec2.dist
Group: 2D Vector
This method returns the distance between two vec2 types
v1 = vec2( 1, 1 )
x = v1:dist( vec2(2, 2) )vector— vec2, compute the distance to this vector
number, distance between this vec2 and vector
Related: vec2
ID: vec2.distSqr
Group: 2D Vector
This method returns the squared distance between two vec2 types
v1 = vec2( 1, 1 )
x = v1:distSqr( vec2(2, 2) )vector— vec2, compute the squared distance to this vector
number, squared distance between this vec2 and vector
Related: vec2
ID: vec2.len
Group: 2D Vector
This method returns the length of a vec2
v1 = vec2( 2, 1 )
x = v1:len()number, length of this vec2
Related: vec2
ID: vec2.lenSqr
Group: 2D Vector
This method returns the squared length of a vec2
v1 = vec2( 2, 1 )
x = v1:lenSqr()number, squared length of this vec2
Related: vec2
ID: vec2.cross
Group: 2D Vector
This method returns the cross product between two vec2 types
v1 = vec2( 1, 1 )
v2 = v1:cross( vec2(2, 2) )vector— compute the cross product with this vector
vec2, cross product of this vec2 and vector
Related: vec2
ID: vec2.rotate
Group: 2D Vector
This method returns a rotated copy of a vec2 type. The angle is assumed to be radians.
v1 = vec2( 1, 1 )
v1 = v1:rotate( math.rad(45) )angle— number, rotate this vector byanglein radians
vec2, rotated version of this vec2
Related: vec2
ID: vec2.rotate90
Group: 2D Vector
This method returns a copy of a vec2 type, rotated 90 degrees.
v1 = vec2( 1, 1 )
v1 = v1:rotate90()vec2, rotated version of this vec2
Related: vec2
ID: vec2.angleBetween
Group: 2D Vector
This method returns the angle between this vec2 and vector in radians.
v1 = vec2( 1, 1 )
angle = math.deg( v1:angleBetween( vec2(5, 2) ) )vector— vec2, compute the angle between thisvec2andvector
number, angle between vec2 and vector in radians
Related: vec2
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.
v = vec2( 1, 2 )
x,y = v:unpack()multiple, two values x, y
pos = vec2(20, 50)
translate( pos:unpack() )Related: vec2
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.
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) * 5x— number, x dimension of this vectory— number, y dimension of this vectorz— number, z dimension of this vector
Related: vec3.dot, vec3.normalize, vec3.dist, vec3.distSqr, vec3.len, vec3.lenSqr, vec3.cross
ID: vec3.dot
Group: 3D Vector
This method returns the scalar dot product between two vec3 types
v1 = vec3( 1, 1, 1 )
x = v1:dot( v )vector— vec3, compute the dot product with this vector
number, dot product between this and vector
Related: vec3
ID: vec3.normalize
Group: 3D Vector
This method returns a normalized version of the vector
v1 = vec3( 5, 5, 5 )
v1 = v1:normalize()vec3, normalized version of this vec3
Related: vec3
ID: vec3.dist
Group: 3D Vector
This method returns the distance between two vec3 types
v1 = vec3( 1, 1, 1 )
x = v1:dist( vec3(2, 2, 2) )vector— vec3, compute the distance to this vector
number, distance between this vec3 and vector
Related: vec3
ID: vec3.distSqr
Group: 3D Vector
This method returns the squared distance between two vec3 types
v1 = vec3( 1, 1, 1 )
x = v1:distSqr( vec3(2, 2, 2) )vector— vec3, compute the squared distance to this vector
number, squared distance between this vec3 and vector
Related: vec3
ID: vec3.len
Group: 3D Vector
This method returns the length of a vec3
v1 = vec3( 2, 1, 0 )
x = v1:len()number, length of this vec3
Related: vec3
ID: vec3.lenSqr
Group: 3D Vector
This method returns the squared length of a vec3
v1 = vec3( 2, 1, 0 )
x = v1:lenSqr()number, squared length of this vec3
Related: vec3
ID: vec3.cross
Group: 3D Vector
This method returns the cross product between two vec3 types
v1 = vec3( 1, 1 )
v2 = v1:cross( vec3(2, 2) )vector— vec3, compute the cross product with this vector
vec3, cross product of this vec3 and vector
Related: vec3
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.
v = vec3( 1, 2, 3 )
x,y,z = v:unpack()multiple, three values x, y, z
myColor = vec3(255, 0, 255)
background( myColor:unpack() )Related: vec3
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.
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) * 5x— number, x dimension of this vectory— number, y dimension of this vectorz— number, z dimension of this vectorw— number, w dimension of this vector
Related: vec4.dot, vec4.normalize, vec4.dist, vec4.distSqr, vec4.len, vec4.lenSqr
ID: vec4.dot
Group: 4D Vector
This method returns the scalar dot product between two vec4 types
v1 = vec4( 1, 1, 1, 1 )
x = v1:dot( v )vector— vec4, compute the dot product with this vector
number, dot product between this vec4 and vector
Related: vec4
ID: vec4.normalize
Group: 4D Vector
This method returns a normalized version of the vector
v1 = vec4( 5, 5, 5, 5 )
v1 = v1:normalize()vec4, normalized version of this vec4
Related: vec4
ID: vec4.dist
Group: 4D Vector
This method returns the distance between two vec4 types
v1 = vec4( 1, 1, 1, 1 )
x = v1:dist( vec4(2, 2, 2, 2) )vector— vec4, compute the distance to this vector
number, distance between this vec4 and vector
Related: vec4
ID: vec4.distSqr
Group: 4D Vector
This method returns the squared distance between two vec4 types
v1 = vec4( 1, 1, 1, 1 )
x = v1:distSqr( vec4(2, 2, 2, 2) )vector— vec4, compute the squared distance to this vector
number, squared distance between this vec4 and vector
Related: vec4
ID: vec4.len
Group: 4D Vector
This method returns the length of a vec4
v1 = vec4( 2, 1, 0, 0 )
x = v1:len()number, length of this vec4
Related: vec4
ID: vec4.lenSqr
Group: 4D Vector
This method returns the squared length of a vec4
v1 = vec4( 2, 1, 0, 0 )
x = v1:lenSqr()number, squared length of this vec4
Related: vec4
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.
v = vec4( 1, 2, 3, 4 )
x,y,z,w = v:unpack()multiple, four values x, y, z, w
myColor = vec4(255, 0, 255, 255)
background( myColor:unpack() )Related: vec4
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
b = bounds(min, max)
b = bounds(vec3(0, 0, 0), vec3(1, 1, 1))min— vec3, the minimum x,y,z range of the area encapsulated by the bounding volumemax— vec3, the maximum x,y,z range of the area encapsulated by the bounding volumevalid— 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 betweenminandmax)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
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
bounds.intersects(other)
bounds.intersects(origin, dir)other— bounds, another bounds value to test for intersection withorigin— vec3, point defining the origin of the ray to test for intersection withdir— vec3, vector describing the ray to test for intersection with
boolean, whether this bounding volume intersects another or the given ray
Related: bounds
ID: bounds.encapsulate
Group: Bounds
This will expand the current bounds to include the given point (vec3)
bounds.encapsulate(point)point— vec3, the bounds will be extended to enclose this point
Related: bounds
ID: bounds.translate
Group: Bounds
Translate (move) the bounds by the specified offset
bounds.translate(offset)offset— vec3, the bounds will offset by this amount
Related: bounds
ID: bounds.set
Group: Bounds
Reset the bounds using the specified min and max values
bounds.set(min, max)min— vec3, the minimum x,y,z range of the area encapsulated by the bounding volumemax— vec3, the maximum x,y,z range of the area encapsulated by the bounding volume
Related: bounds
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.
matrix[1] ... matrix[16]
m = matrix()
m = matrix(1, 2, 3, ... 16)
m = matrix1 * matrix2A new matrix with the given elements
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
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.
rotated = m:rotate( angle, axisX, axisY, axisZ )angle— number, the rotation in degreesaxisX— number, the x component of the axis of rotationaxisY— number, the y component of the axis of rotationaxisZ— number, the z component of the axis of rotation
matrix, a matrix which rotates m by the specified rotation
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
ID: matrix.translate
Group: Matrix
This method returns the matrix multiplied by a translation matrix defining a translation of x, y, z.
translated = m:translate( x, y, z )x— number, the x component of translationy— number, the y component of translationz— number, optional (defaults to 0) the z component of translation"
matrix, a matrix which translates m by the specified amount
m = matrix()
translated = m:translate(100,20,10)Related: matrix
ID: matrix.scale
Group: Matrix
This method returns the matrix scaled by a translation matrix defining a scaling to each axis.
scaled = m:scale( x, y, z )x— number, the x component of scale, or the uniform scale if no other components are giveny— number, optional, the y component of scalez— number, optional, defaults to 1 if x and y are both given, otherwise x minus the z component of scale
matrix, a matrix which scales m by the specified amount
m = matrix()
s = m:scale(100,20,10)
--Uniform scaling
s = m:scale(5)Related: matrix
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.
inv = m:inverse()matrix, a matrix which inverts m
Related: matrix
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.
transposed = m:transpose()matrix, a matrix which is the transpose of m
Related: matrix
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.
det = m:determinant()number, a number equal to the determinant of m
Related: matrix
ID: quat
Group: Quaternion
This type represents a quaternion.
quat.x
quat.y
quat.z
quat.w
myQuat = quat.eulerAngles(45,45,45)x— number, x dimension of this quaterniony— number, y dimension of this quaternionz— number, z dimension of this quaternionw— number, w dimension of this quaternion
Related: quat.slerp, quat.angles, quat.angleAxis, quat.eulerAngles, quat.lookRotation, quat.fromToRotation
ID: quat.eulerAngles
Group: Quaternion
Creates a new quaternion using 3 euler angles given in degrees.
q = quat.eulerAngles(45,0,45)x— number, the amount of pitch in degreesy— number, the amount of roll in degreesz— number, the amount of yaw in degrees
quat, the resulting quaternion
Related: quat
ID: quat.angleAxis
Group: Quaternion
Creates a new quaternion using an angle and axis.
q = quat.angleAxis(45, vec3(0,0,1))angle— float, the amount of rotation about the axis in degreesaxis— vec3, the axis to rotate around
quat, the resulting quaternion
Related: quat
ID: quat.lookRotation
Group: Quaternion
Creates a new quaternion that 'looks' in a specified direction.
q = quat.lookRotation( vec3(0,0,1), vec3(0,1,0) )forward— vec3, the direction to look atup— vec3, the upwards direction used to orient the quaternion
quat, the resulting quaternion
Related: quat
ID: quat.fromToRotation
Group: Quaternion
Creates a new quaternion that rotates between two directions.
q = quat.fromToRotation( vec3(0,0,1), vec3(1,0,0) )from— vec3, the start directionto— vec3, the the end direction
quat, the resulting quaternion
Related: quat
ID: quat.slerp
Group: Quaternion
Performs spherical interpolation (slerp) from this quaternion to another.
q1 = quat.eulerAngles(0,0,0)
q2 = quat.eulerAngles(0,0,90)
q3 = q1:slerp(p2, 0.5)q— quat, the quaternion to interpolate towardst— number, the amount of interpolation to perform
quat, the spherically interpolated quaternion
Related: quat
ID: quat.angles
Group: Quaternion
Extracts the euler angles from a quaternion and returns them as a vec3 in degrees.
q = quat.eulerAngles(20,30,40)
angles = q:angles()vec3, the euler angles for this quaternion in degrees
Related: quat
ID: quat.normalized
Group: Quaternion
Returns a normalized copy of this quaternion
q = quat.eulerAngles(20,30,40)
nq = q:normalized()quat, a normalized version of this quaternion
Related: quat, quat.normalize
ID: quat.normalize
Group: Quaternion
Normalize this quaternion
q = quat.eulerAngles(20,30,40)
q:normalize()Related: quat, quat.normalized
ID: quat.conjugate
Group: Quaternion
Return the conjugation of this quaternion
q = quat.eulerAngles(20,30,40)
cq = q:conjugate()quat, a conjugated version of this quaternion
Related: quat
ID: quat.len
Group: Quaternion
Return the length of this quaternion
q = quat.eulerAngles(20,30,40)
len = q:len()number, the length of this quaternion
Related: quat, quat.lenSqr
ID: quat.lenSqr
Group: Quaternion
Return the squared length of this quaternion
q = quat.eulerAngles(20,30,40)
len2 = q:lenSqr()number, the squared length of this quaternion
Related: quat, quat.len