Documenti di Didattica
Documenti di Professioni
Documenti di Cultura
www.GiderosMobile.com
Gideros API Contributors
Contents
Simple examples
a={{1,2,3},{4,5,6},{7,8,9}}
b=a[2,2] -- b will be 5, easier to read than b=[a][b]
a[2,2]=7 -- same as a[2][2]=7
Simple examples
a=0b00000001 -- a=1
a=0b00000010 -- a=2
a=0b00000011 -- a=3
a=0b00000100 -- a=4
a=0b00000101 -- a=5
a=0b00000110 -- a=6
a=0b00000111 -- a=7
a=0b00001000 -- a=8
a=0b00001001 -- a=9
local deltaX={0,-1,1,0,0,-1,1,0,0,-1,1,0,0,-1,1,0}
local deltaY={0,0,0,0,1,1,1,1,-1,-1,-1,-1,0,0,0,0}
x=x+deltaX[joypad+1]
y=y+deltaY[joypad+1]
joypad=(joypad~joypadOld)&joypad
joypadOld=joypad
Simple example
x=(x<>min)><max
pi@3.14159265358979324
num1 @ -100.54
num2 @ 232
num3 @ 444.10
str1 @ 'hello'
str2 @ "world"
str3 @ [[
Hello,
world!
]]
print @ |--|
Enumeration
enum @ (|
local t=...
local r={}
for i=1, #t, 2 do
table.insert(r, t[i] .. " @ " .. i // 2+1)
end
print(table.concat(r, " "))
return table.concat(r, " ")
|)
Unroll loops
dotimes @ (|
local times=table.remove(..., 1)
return (table.concat(..., " ").." "):rep(times)
|)
Simple examples
a=0o10 -- a=8
a=0o112 -- a=74
Example:
--create instance
local accelerometer=Accelerometer.new()
--start receiving data
accelerometer:start()
---get values for example on each enter frame event
local x, y, z=accelerometer:getAcceleration()
print(x, y, z)
Example:
local alertDialog=AlertDialog.new('This is my title', 'And my message', 'Cancel', 'Yes', 'No')
alertDialog:addEventListener(Event.COMPLETE, onComplete)
alertDialog:show()
Parameter:
logical : (bool) Returns the margin in logical scale if set to true.
Results:
num : Minimum x
num : Minimum y
num : Maximum x
num : Maximum y
Example:
application:setKeepAwake(true) -- disable screen dimming and device sleeping
application:setKeepAwake(false) -- enable screen dimming and device sleeping
Parameter:
visible : (bool) if the keyboard should be shown
Result:
bool : true if the device support a native on screen keyboard
Example:
local texture=Texture.new('image.png')
local bitmap1=Bitmap.new(texture)
local bitmap2=Bitmap.new(region)
stage:addChild(bitmap1)
stage:addChild(bitmap2)
Example:
MySprite=Core.class(Sprite)
--my custom sprite class
function MySprite:init()
end
Parameters:
generator : (num) PRNG algorithm to use, use 0 for default engine (MT19937)
bound1 : (num) First bound of the range returned number must be in
bound2 : (num) Second bound of the range returned number must be in
Result:
random number
Parameters:
generator : (num) PRNG algorithm to use, use 0 for default engine (MT19937)
seed : (num) Seed for that generator
Result:
A seed usable for later resuming the RNG
Parameters:
ciphertext : (str) AES128 encrypted message
key : (str) encryption key as a 16 byte string
iv : (str) a 16 byte IV to be used for CBC mode. If not provided ECB mode is used.
paddingType : (num) Type of padding to be used. Currently defined values are:</br><ul><li>0: 0 padding
</li><li>1: PKCS7 padding</li></ul>
Result:
str : deciphered message
Parameters:
plaintext : (str) The message to be encrypted
key : (str) encryption key as a 16 byte string
iv : (str) a 16 byte IV to be used for CBC mode. If not provided ECB mode is used.
paddingType : (num) Type of padding to be used. Currently defined values are:</br><ul><li>0: 0 padding
</li><li>1: PKCS7 padding</li></ul>
Result:
str : ciphered message
Parameter:
input : (str) String whose content is to be hashed
Result:
str : MD5 hash (a 16 byte string)
Parameter:
type : (str)
Results:
any : New `Event` object.
any : New `Event` object.
Example:
-- example 1
ClassA=Core.class(EventDispatcher)
ClassB=Core.class(EventDispatcher)
function ClassA:funcA(event)
print('funcA', self, event:getType(), event:getTarget())
end
local a=ClassA.new()
local b=ClassB.new()
-- example 2
Ball=Core.class(Sprite)
function Ball:onEnterFrame()
self:setX(self:getX() 1)
end
ball=Ball.new()
ball:addEventListener(Event.ENTER_FRAME, ball.onEnterFrame, ball)
Parameter:
type : (str) The type of event.
Result:
bool : A value of `true` if a listener of the specified type is registered; `false` otherwise.
Parameters:
text : (str)
letterSpacing : (number, default = 0)
size : (number, optional)
Result:
num : The width of the first size characters of text.
Parameter:
text : (str)
Results:
num : x coordinate of the bound
num : y coordinate of the bound
num : width of the bound
num : height of the bound
Parameters:
text : (str)
width : (num)
height : (num)
flags : (number, default=FontBase.TLF_NOWRAP)
letterSpacing : (number, default = 0)
lineSpacing : (number, default = 0)
tabSpace : (number, default = 4)
Result:
table : A table describing how to draw the given text.
Example:
geolocation=Geolocation.new()
geolocation:addEventListener(Event.LOCATION_UPDATE, onLocationUpdate)
geolocation:addEventListener(Event.HEADING_UPDATE, onHeadingUpdate)
geolocation:start()
Example:
local gyroscope=Gyroscope.new()
gyroscope:start()
local angx=0
local angy=0
local angz=0
local function onEnterFrame(event)
local x, y, z=gyroscope:getRotationRate()
angx=angx x*event.deltaTime
angy=angy y*event.deltaTime
angz=angz z*event.deltaTime
stage:addEventListener('enterFrame', onEnterFrame)
JS . eval BETA
execute arbitrary Javascript code on HTML5 platform
JS.eval(code)
code : (str) JavaScript code to execute
Parameters:
m11 : (number, default = 1)
m12 : (number, default = 0)
m21 : (number, default = 0)
m22 : (number, default = 1)
tx : (number, default = 0)
ty : (number, default = 0)
Results:
any : New `Matrix` object.
any : New `Matrix` object.
Mesh usage
local mesh=Mesh.new()
stage:addChild(mesh)
-- 1. vertex (0, 0)
-- 2. vertex (100, 0)
-- 3. vertex (100, 150)
-- 4. vertex (0, 150)
mesh:setVertexArray(0, 0, 100, 0, 100, 150, 0, 150)
Parameter:
i : (num) index
Results:
num : color
num : normalizes alpha (0-1)
Parameter:
i : (num) index
Result:
num : index of element
Parameter:
i : (num) index
Parameter:
i : (num) index
Results:
num : x coordinate of vertex
num : y coordinate of vertex
Example:
-- set the first 3 colors as (0xff0000, 0.5), (0x00ff00, 0.7) and (0x0000ff, 1.0).
mesh:setColor(1, 0xff0000, 0.5) -- red with 0.5 alpha
mesh:setColor(2, 0x00ff00, 0.7) -- green with 0.7 alpha
mesh:setColor(3, 0x0000ff) -- blue with 1.0 alpha
Example:
-- set the color array as (0xff0000, 0.5), (0x00ff00, 0.7) and (0x0000ff, 1.0).
mesh:setColorArray(0xff0000, 0.5, 0x00ff00, 0.7, 0x0000ff, 1.0)
-- same as above
mesh:setColorArray{0xff0000, 0.5, 0x00ff00, 0.7, 0x0000ff, 1.0}
Example:
-- set 3 colors with seperate function calls
-- same as above
mesh:setColors{1, 0xff0000, 0.5, 2, 0x00ff00, 0.7, 3, 0x0000ff, 1.0}
Example:
-- set the first 3 indices as 10, 11 and 12.
mesh:setIndex(1, 10)
mesh:setIndex(2, 11)
mesh:setIndex(3, 12)
Example:
-- set the index array as 10, 11 and 12.
mesh:setIndexArray(10, 11, 12)
-- same as above
Example:
-- set 3 indices with seperate function calls
mesh:setIndex(1, 10)
mesh:setIndex(2, 11)
mesh:setIndex(3, 12)
-- same as above
mesh:setIndices{1, 10, 2, 11, 3, 12}
Example:
-- set the first 3 texture coordinates as (0, 0), (100, 0) and (0, 100).
mesh:setTextureCoordinate(1, 0, 0)
mesh:setTextureCoordinate(2, 100, 0)
mesh:setTextureCoordinate(3, 0, 100)
Example:
-- set the color array as (0, 0), (100, 0) and (0, 100)
mesh:setTextureCoordinateArray(0, 0, 100, 0, 0, 100)
-- same as above
mesh:setTextureCoordinateArray{0, 0, 100, 0, 0, 100}
Mesh:setTextureCoordinates(textureCoordinates)
textureCoordinates : (any) Sets zero or more texture coordinates at texture coordinate array with a single
function call. It accepts multiple values or a Lua array.
Example:
-- set 3 texture coordinates with seperate function calls
mesh:setTextureCoordinate(1, 0, 0)
mesh:setTextureCoordinate(2, 100, 0)
mesh:setTextureCoordinate(3, 0, 100)
-- same as above
mesh:setTextureCoordinates{1, 0, 0, 2, 100, 0, 3, 0, 100}
Example:
-- set the first 3 vertex positions as (100, 100), (150, 100) and (100, 150).
mesh:setVertex(1, 100, 100)
mesh:setVertex(2, 150, 100)
mesh:setVertex(3, 100, 150)
Example:
-- set the vertex array as (100, 100), (150, 100) and (100, 150)
mesh:setVertexArray(100, 100, 150, 100, 100, 150)
-- same as above
mesh:setVertexArray{100, 100, 150, 100, 100, 150}
Example:
-- set 3 vertices with seperate function calls
mesh:setVertex(1, 100, 100)
mesh:setVertex(2, 150, 100)
mesh:setVertex(3, 100, 150)
-- same as above
mesh:setVertices{1, 100, 100, 2, 150, 100, 3, 100, 150}
Example:
-- construct a 100 frame animation where x coordinate of sprite tweens from 0 to 200 linearly
local mc=MovieClip.new{
{1, 100, sprite, {x={0, 200, "linear"}}}
}
-- construct a 200 frame animation where sprite1 and sprite2 tweens differently
-- here sprite1 is visible between frames [1, 150]
-- and sprite2 is visible between frames [100, 200]
local mc=MovieClip.new{
{1, 100, sprite1, {x={0, 200, "linear"}}},
{50, 150, sprite1, {y={0, 100, "linear"}, alpha={0, 1, "easeOut"}}},
{100, 200, sprite2, {x={0, 200, "linear"}}},
}
-- construct a looping 6 frame animation playing 5 times slower than the previous example
local mc=MovieClip.new{
{1, 5, frame1},
Example usage
local bmp=Bitmap.new("image.png")
print(bmp:getClass()) -- prints Bitmap
print(bmp:getBaseClass()) -- prints Sprite
print(bmp:isInstanceOf("Bitmap")) -- prints true
print(bmp:isInstanceOf("Sprite")) -- prints true
print(bmp:isInstanceOf("EventDispatcher")) -- prints true
print(bmp:isInstanceOf("Object")) -- prints true
print(bmp:isInstanceOf("TileMap")) -- prints false
Parameter:
classname : (str) The name of the class to check relation to
Result:
bool : true if instance belongs or inherits from class, false otherwise
Parameter:
particles : (table or arguments) table for multiple particles or arguments for single
Result:
number or table : index or table with indexes of added particles
Parameter:
i : (num) index of particle
Result:
num : angle of particle in degrees
Parameter:
i : (num) particle index
Results:
Parameter:
i : (num) particle index
Results:
num : speed decay factor
num : alpha decay factor
num : growth speed decay factor
num : angular speed decay factor
Parameter:
i : (num) index of particle
Results:
num : x position
num : y position
Parameters:
set : (table) Optional set of particle indices to query
tag : (str) only return particles matching this tag
Result:
table : table containing the state of each particle in the system matching tag if any
Parameter:
i : (num) index of particle
Result:
num : size in pixels
Parameter:
i : (num) particle index
Results:
num : x vector
num : y vector
num : angular velocity
num : growth speed
Parameter:
i : (num) particle index
Result:
str : tag
Parameter:
i : (num) index of particle
Result:
num : initial time to live in seconds
Drawing Moon
--Moon
local p=Path2D.new()
local ms="MQQZ" --MoveTo, QuadTo, QuadTo, Close
local mp={100,0, -50,100, 100,200, 20,100, 100,0 }
p:setPath(ms,mp) --Set the path from a set of commands and coordinates
p:setLineThickness(3) -- Outline width
p:setFillColor(0xE0E0E0,0.7) --Fill color
p:setLineColor(0xC0C0C0) --Line color
p:setAnchorPosition(100,100)
stage:addChild(p)
Drawing banana
--Banana shape, SVG path format
local
banana="M8.64,223.948c0,0,143.468,3.431,185.777-181.808c2.673-11.702-1.23-20.154,1.316-33.146h16.2
87c0,0-3.14,17.248,1.095,30.848c21.392,68.692-4.179,242.343-204.227,196.59L8.64,223.948z"
p=Path2D.new()
p:setSvgPath(banana) --Set the path from a SVG path description
p:setLineThickness(5) -- Outline width
p:setFillColor(0xFFFF80,0.7) --Fill color
p:setLineColor(0x404000) --Line color
p:setAnchorPosition(100,100)
stage:addChild(p)
Drawing Moon
--Moon
local p=Path2D.new()
local ms="MQQZ" --MoveTo, QuadTo, QuadTo, Close
local mp={100,0, -50,100, 100,200, 20,100, 100,0 }
p:setPath(ms,mp) --Set the path from a set of commands and coordinates
p:setLineThickness(3) -- Outline width
p:setFillColor(0xE0E0E0,0.7) --Fill color
p:setLineColor(0xC0C0C0) --Line color
p:setAnchorPosition(100,100)
stage:addChild(p)
Drawing banana
--render target
local rt=RenderTarget.new(source:getWidth(), source:getHeight())
Parameters:
x : (num) x coordinate of pixel
y : (num) y coordinate of pixel
Results:
num : color in hex
num : alpha value from 0 to 1
Parameters:
x : (num) x coordinate of pixel
y : (num) y coordinate of pixel
w : (num) width of rectangle to include in buffer
h : (num) height of rectangle to include in buffer
Result:
buffer : buffer with color and alpha data
Shader example
--Shaders are in vShader.glsl and fShader.glsl files
local shader=Shader.new("vShader","fShader",0, {
{name="vMatrix",type=Shader.CMATRIX,sys=Shader.SYS_WVP,vertex=true},
{name="fColor",type=Shader.CFLOAT4,sys=Shader.SYS_COLOR,vertex=false},
{name="fTexture",type=Shader.CTEXTURE,vertex=false},
{name="fTexelSize",type=Shader.CFLOAT4,vertex=false},
{name="fRad",type=Shader.CINT,vertex=false}, },
{ {name="vVertex",type=Shader.DFLOAT,mult=3,slot=0,offset=0},
{name="vColor",type=Shader.DUBYTE,mult=4,slot=1,offset=0},
{name="vTexCoord",type=Shader.DFLOAT,mult=2,slot=2,offset=0}, });
sprite:setShader(shader)
Shader example
--Shaders are in vShader.glsl and fShader.glsl files
local shader=Shader.new("vShader","fShader",0, {
{name="vMatrix",type=Shader.CMATRIX,sys=Shader.SYS_WVP,vertex=true},
{name="fColor",type=Shader.CFLOAT4,sys=Shader.SYS_COLOR,vertex=false},
{name="fTexture",type=Shader.CTEXTURE,vertex=false},
{name="fTexelSize",type=Shader.CFLOAT4,vertex=false},
sprite:setShader(shader)
Example:
setFillStyle(Shape.NONE) -- clears the fill style
setFillStyle(Shape.SOLID, 0xff0000, 0.5) -- sets the fill style as solid red color with 0.5
transparency
local texture=Texture.new('image.png')
setFillStyle(Shape.TEXTURE, texture) -- sets the fill style as texture with 'image.png'
Example:
local sound=Sound.new('music.mp3')
local channel=sound:play()
Parameters:
startTime : (number, default = 0) The initial position in milliseconds at which playback should start.
looping : (boolean, default = false)
Result:
SoundChannel : A `SoundChannel` object, which you use to control the sound. This function returns `nil` if
you run out of available sound channels.
Parameter:
child : (Sprite) The child object to test.
Result:
bool : `true` if the child object is contained in the subtree of this `Sprite` instance, otherwise `false`.
Parameter:
param : (str) The name of the parameter
Result:
num : The value of the parameter
Example:
-- the following two lines do the same thing
x=sprite:getX()
x=sprite:get('x')
Results:
num : x coordinate
num : y coordinate
num : width of Sprite
num : height of Sprite
Example:
local x, y, width, height=sprite:getBounds(sprite) -- returns local (untransformed) bounds
local x, y, width, height=sprite:getBounds(stage) -- returns bounds as transformed to stage's
coordinate system
Parameter:
index : (num) The index position of the child object.
Result:
Sprite : The child sprite at the specified index position.
Parameter:
child : (Sprite) The child sprite to identify.
Result:
num : The index of the specified child sprite.
Parameter:
withoutTransform : (bool) If true, return the height without transformation, else return the transformed height
Result:
num : Height of the sprite.
Example:
local container1=Sprite.new()
local container2=Sprite.new()
local sprite1=Sprite.new();
local sprite2=Sprite.new();
container2:addChild(container1)
container1:addChild(sprite1)
container1:addChild(sprite2)
print(container1:getNumChildren()) --> 2
print(container2:getNumChildren()) --> 1
print(sprite1:getNumChildren()) --> 0
print(sprite2:getNumChildren()) --> 0
Parameter:
withoutTransform : (bool) If true, return the width of the Sprite without transformations else return the
transformed width
Results:
any : Width of the sprite.
any : Width of the sprite.
Parameters:
x : (num) x coordinate of the global coordinate.
y : (num) y coordinate of the global coordinate.
Results:
num : 1. x coordinate relative to the display object.
num : 2. y coordinate relative to the display object.
Parameters:
x : (num)
y : (num)
shapeFlag : (bool) Take clipping/masking into consideration when testing hit point
Result:
bool : `true` if the given global coordinates are in bounds of the sprite, `false` otherwise.
Parameters:
x : (num) x coordinate of the local coordinate.
y : (num) y coordinate of the local coordinate.
Results:
num : 1. x coordinate relative to the display area.
num : 2. y coordinate relative to the display area.
Example:
-- the following two lines do the same thing
sprite:setX(10)
sprite:set('x', 10)
Example:
local font=Font.new('myfont.txt', 'myfont.png')
stage:addChild(textfield)
-- to use the default font, pass nil value for the font parameter
local textfield2=TextField.new(nil, 'some other text with default font')
num = TextField:getTextColor()
num : The color of the text in a text field, in hexadecimal format.
Example:
textfield:setTextColor(0xff0000) -- red
textfield:setTextColor(0x00ff00) -- green
textfield:setTextColor(0x0000ff) -- blue
Example:
local textInputDialog=TextInputDialog.new('my title', 'my message', 'some text', 'Cancel', 'OK')
textInputDialog:addEventListener(Event.COMPLETE, onComplete)
textInputDialog:show()
Example:
local texture=Texture.new('image.png', false, {transparentColor=0xff00ff}) -- do not filter and
make the color 0xff00ff transparent
local texture=Texture.new('image.png', true, {wrap=Texture.REPEAT}) -- enable filtering and
repeat the texture
Example:
local texture=Texture.new(nil,300,400;, false, {extend=false}) -- Create a 300x400 empty texture.
Prevent gideros from extending the texture to the next power of two size
Example:
local texture=Texture.new('image.png', false, {transparentColor=0xff00ff}) -- do not filter and
make the color 0xff00ff transparent
local texture=Texture.new('image.png', true, {wrap=Texture.REPEAT}) -- enable filtering and
repeat the texture
Example:
local texture=Texture.new(nil,300,400;, false, {extend=false}) -- Create a 300x400 empty texture.
Prevent gideros from extending the texture to the next power of two size
Parameter:
texturename : (str)
Result:
TextureRegion : TextureRegion by specified name
Example:
local pack=TexturePack.new({'gfx/1.png', 'gfx/2.png', 'gfx/3.png', 'gfx/4.png'})
local region1=pack:getTextureRegion('gfx/1.png')
local region2=pack:getTextureRegion('gfx/2.png')
local region3=pack:getTextureRegion('gfx/3.png')
local region4=pack:getTextureRegion('gfx/4.png')
Example:
local texture=Texture.new('atlas.png')
stage:addChild(bitmap1)
stage:addChild(bitmap2)
stage:addChild(bitmap3)
stage:addChild(bitmap4)
Parameters:
x : (num) The x-position of tile
y : (num) The y-position of tile
Results:
num : x tile position of texture or nil if tile is not set
num : y tile position of texture or nil if tile is not set
num : flip flag (TileMap.FLIP_DIAGONAL, TileMap.FLIP_HORIZONTAL, TileMap.FLIP_VERTICAL) of tile or
nil if tile is not set
Example:
tilemap:shift(-1, 0) -- shifts the tile map to the left
tilemap:shift(1, 0) -- shifts the tile map to the right
tilemap:shift(0, -1) -- shifts the tile map to the up
tilemap:shift(0, 1) -- shifts the tile map to the down
Parameters:
delay : (num) Delay in miliseconds before the function is called
func : (function) Function to call
data : (any) An optional data parameter that is passed as a first argument to the function
Result:
Timer : The `Timer` object
Example:
local font=TTFont.new("tahoma.ttf", 30)
The example below shows downloading an image file from an URL, saving it to the documents folder and
displaying it
on the stage. This example also shows downloading progress and handling errors.
local loader=UrlLoader.new('http://example.com/image.png')
local b=Bitmap.new(Texture.new('|D|image.png'))
stage:addChild(b)
end
loader:addEventListener(Event.COMPLETE, onComplete)
loader:addEventListener(Event.ERROR, onError)
loader:addEventListener(Event.PROGRESS, onProgress)
Uploading a file
local filename="crate.png"
local file=io.open(filename, "rb")
local contents=file:read( "*a" )
local boundary="somerndstring"
local send="--"..boundary..
"\r\nContent-Disposition: form-data; "..
"name="..filename.."; filename="..filename..
"\r\nContent-type: image/png"..
"\r\n\r\n"..contents..
local headers={
["Content-Type"]="multipart/form-data; boundary="..boundary,
["Content-Length"]=#send,
}
loader:addEventListener(Event.COMPLETE, function(e)
print(e.data)
end)
Example:
local url='http://www.[yourDomain].com/application.php?userid=gideros&login=guest'
local loader1=UrlLoader.new(url)
local loader2=UrlLoader.new(url, UrlLoader.GET) -- same as the previous line
local loader3=UrlLoader.new(url, UrlLoader.POST, 'my post data')
local loader4=UrlLoader.new(url, UrlLoader.PUT, 'my put data')
local loader5=UrlLoader.new(url, UrlLoader.DELETE)
local headers={
['Content-Type']='application/x-www-form-urlencoded',
['User-Agent']='Gideros Browser',
}
local loader6=UrlLoader.new(url, UrlLoader.PUT, headers, 'key=value')
b2 . createDistanceJointDef 2011.6+
Creates and returns a distance joint definition table with the bodies, anchors, and length using the world
anchors.(Please refer to [[b2.World:createJoint]] function for more information about all the information
needed to create a distance joint).
table = b2.createDistanceJointDef(bodyA, bodyB, anchorAx, anchorAy, anchorBx, anchorBy)
Parameters:
bodyA : (b2.Body) the first attached body
bodyB : (b2.Body) the second attached body
anchorAx : (num) the x coordinate of the world anchor point of bodyA
anchorAy : (num) the y coordinate of the world anchor point of bodyA
anchorBx : (num) the x coordinate of the world anchor point of bodyB
anchorBy : (num) the y coordinate of the world anchor point of bodyB
Result:
table : A new distance joint definition table
Distance joint
local jointDef=b2.createDistanceJointDef(body1, body2, 100, 100, 200, 100)
local distanceJoint=world:createJoint(jointDef)
--by default length between two bodies is the length they have between them when joint was
created
--but it is possilbe to change it using
distanceJoint:setLength(200)
distanceJoint:setDampingRatio(0.5)
distanceJoint:setFrequency(4)
b2 . createFrictionJointDef 2011.6+
Creates and returns a friction joint definition table with the bodies and local anchors using a world anchor
point.(Please refer to [[b2.World:createJoint]] function for more information about all the information needed
to create a friction joint).
table = b2.createFrictionJointDef(bodyA, bodyB, anchorx, anchory)
Parameters:
bodyA : (b2.Body) the first attached body
bodyB : (b2.Body) the second attached body
anchorx : (num) the x coordinate of the world anchor point
anchory : (num) the y coordinate of the world anchor point
Result:
table : A new friction joint definition table
Friction joint
--create empty box2d body for joint
local ground=world:createBody({})
ground:setPosition(350, 480)
b2 . createGearJointDef 2011.6+
Creates and returns a gear joint definition table.(Please refer to [[b2.World:createJoint]] function for more
information about all the information needed to create a gear joint).
table = b2.createGearJointDef(bodyA, bodyB, joint1, joint2, ratio)
Parameters:
bodyA : (b2.Body) the first attached body
bodyB : (b2.Body) the second attached body
joint1 : (b2.Joint) the first revolute/prismatic joint attached to the gear joint
joint2 : (b2.Joint) the second revolute/prismatic joint attached to the gear joint
ratio : (number, default = 1) the gear ratio
Result:
table : A new gear joint definition table
b2 . createMouseJointDef 2011.6+
Creates and returns a mouse joint definition table with the bodies, world target point, maxForce and optional
frequencyHz and dampingRatio.(Please refer to [[b2.World:createJoint]] function for more information about
all the information needed to create a mouse joint).
Parameters:
bodyA : (b2.Body) the first attached body
bodyB : (b2.Body) the second attached body
targetx : (num) the x coordinate of the world target point
targety : (num) the y coordinate of the world target point
maxForce : (num) the maximum constraint force that can be exerted to move the candidate body
frequencyHz : (number, default = 5) the response speed
dampingRatio : (number, default = 0.7) the damping ratio. 0 = no damping, 1 = critical damping
Result:
table : A new mouse joint definition table
Mouse joint
--create empty box2d body for joint
local ground=world:createBody({})
b2 . createPrismaticJointDef 2011.6+
Creates and returns a prismatic joint definition table with the bodies, anchors, axis, and reference angle using
the world anchor and world axis.(Please refer to [[b2.World:createJoint]] function for more information about
all the information needed to create a prismatic joint).
table = b2.createPrismaticJointDef(bodyA, bodyB, anchorx, anchory, axisx, axisy)
Parameters:
bodyA : (b2.Body) the first attached body
bodyB : (b2.Body) the second attached body
anchorx : (num) the x coordinate of the world anchor point
anchory : (num) the y coordinate of the world anchor point
Result:
table : A new prismatic joint definition table
Prismatic joint
--create empty box2d body for joint
local ground=world:createBody({})
ground:setPosition(465, 480)
b2 . createPulleyJointDef 2011.6+
Creates and returns a pulley joint definition table with the bodies, anchors, lengths, max lengths, and ratio
using the world anchors.(Please refer to [[b2.World:createJoint]] function for more information about all the
information needed to create a pulley joint).
table = b2.createPulleyJointDef(bodyA, bodyB, groundAnchorAx, groundAnchorAy, groundAnchorBx,
groundAnchorBy, anchorAx, anchorAy, anchorBx, anchorBy, ratio)
Parameters:
bodyA : (b2.Body) the first attached body
bodyB : (b2.Body) the second attached body
groundAnchorAx : (num) the x coordinate of the first ground anchor in world coordinates. This point never
moves.
groundAnchorAy : (num) the y coordinate of the first ground anchor in world coordinates. This point never
moves.
groundAnchorBx : (num) the x coordinate of the second ground anchor in world coordinates. This point never
moves.
groundAnchorBy : (num) the y coordinate of the second ground anchor in world coordinates. This point never
moves.
anchorAx : (num) the x coordinate of the world anchor point of bodyA
anchorAy : (num) the y coordinate of the world anchor point of bodyA
anchorBx : (num) the x coordinate of the world anchor point of bodyB
anchorBy : (num) the y coordinate of the world anchor point of bodyB
ratio : (num) the pulley ratio, used to simulate a block-and-tackle
Result:
table : A new pulley joint definition table
Pulley joint
--create empty box2d body for joint
local ground=world:createBody({})
b2 . createRevoluteJointDef 2011.6+
Creates and returns a revolute joint definition table with the bodies, local anchors, and reference angle using
a world anchor point.(Please refer to [[b2.World:createJoint]] function for more information about all the
information needed to create a revolute joint).
table = b2.createRevoluteJointDef(bodyA, bodyB, anchorx, anchory)
Parameters:
bodyA : (b2.Body) the first attached body
bodyB : (b2.Body) the second attached body
anchorx : (num) the x coordinate of the world anchor point
anchory : (num) the y coordinate of the world anchor point
Result:
table : A new revolute joint definition table
Example:
local jointdef=b2.createRevoluteJointDef(bodyA, bodyB, anchorx, anchory)
local joint=b2.World:createJoint(jointdef)
Revolute joint
--create empty box2d body for joint
local ground=world:createBody({})
ground:setPosition(300, 480)
b2 . createRopeJointDef 2012.09.3+
Creates and returns a rope joint definition table with the bodies and local anchors using a world anchor
point.(Please refer to [[b2.World:createJoint]] function for more information about all the information needed
to create a rope joint).
table = b2.createRopeJointDef(bodyA, bodyB, anchorAx, anchorAy, anchorBx, anchorBy, maxLength)
Parameters:
bodyA : (b2.Body) the first attached body
bodyB : (b2.Body) the second attached body
anchorAx : (num) the x coordinate of the world anchor point of bodyA
anchorAy : (num) the y coordinate of the world anchor point of bodyA
anchorBx : (num) the x coordinate of the world anchor point of bodyB
anchorBy : (num) the y coordinate of the world anchor point of bodyB
maxLength : (num) the maximum length of the rope
Result:
table : A new rope joint definition table
Parameters:
bodyA : (b2.Body) the first attached body
bodyB : (b2.Body) the second attached body
anchorAx : (num) the x coordinate of the world anchor point of bodyA
anchorAy : (num) the y coordinate of the world anchor point of bodyA
anchorBx : (num) the x coordinate of the world anchor point of bodyB
anchorBy : (num) the y coordinate of the world anchor point of bodyB
Result:
table : A new weld joint definition table
Weld joint
local jointDef=b2.createWeldJointDef(body1, body2, 100, 100, 130, 100)
local weldJoint=world:createJoint(jointDef)
b2 . createWheelJointDef 2011.6+
Creates and returns a wheel joint definition table.(Please refer to [[b2.World:createJoint]] function for more
information about all the information needed to create a wheel joint).
table = b2.createWheelJointDef(bodyA, bodyB, anchorx, anchory, axisx, axisy)
Parameters:
bodyA : (b2.Body) the first attached body
bodyB : (b2.Body) the second attached body
anchorx : (num) the x coordinate of the world anchor point
anchory : (num) the y coordinate of the world anchor point
axisx : (num) the x coordinate of the world translation axis in bodyA
axisy : (num) the y coordinate of the world translation axis in bodyA
Result:
table : A new wheel joint definition table
Wheel joint
--create empty box2d body for joint
local ground=world:createBody({})
ground:setPosition(350, 480)
b2 . getScale 2011.6+
b2 . setScale 2011.6+
Box2D is tuned for MKS (meters-kilogram-second) units and the size of moving objects should roughly
between 0.1 and 10 meters.If you directly use the pixels as your units, unfortunately this will lead to a poor
simulation and possibly weird behavior.Gideros uses an internal scale system to convert between meters
and pixels. By default, the value of this scale is 30which means 1 meter = 30 pixels. This is a global value
and effects all the physics system. Therefore, it is recommended to set thisvalue once before any physical
objects are instantiated (e.g. right after calling `require 'box2d'`)
b2.setScale(scale)
scale : (num) - the global pixels to meters scale
ball:setPosition(100,100)
--get radius
local radius=ball:getWidth()/2
--add to scene
stage:addChild(ball)
stage:addEventListener(Event.ENTER_FRAME, function()
-- edit the step values if required. These are good defaults!
world:step(1/60, 8, 3)
ball:setPosition(ball.body:getPosition())
ball:setRotation(math.rad(ball.body:getAngle()))
end)
Parameter:
fixtureDef : (table)
Result:
b2.Fixture : The created fixture instance.
Results:
num : x coordinate of the provided point expressed in local coordinates
num : y coordinate of the provided point expressed in local coordinates
Parameters:
x : (num) x coordinate of the world vector
y : (num) y coordinate of the world vector
Results:
num : x vector of the provided vector expressed in local coordinates
num : y vector of the provided vector expressed in local coordinates
Parameters:
x : (num) x coordinate of the local point
y : (num) y coordinate of the local point
Results:
num : x coordinate of the provided point expressed in world coordinates
num : y coordinate of the provided point expressed in world coordinates
Parameters:
x : (num) x coordinate of the local vector
y : (num) y coordinate of the local vector
Results:
num : x vector of the provided vector expressed in world coordinates
num : x vector of the provided vector expressed in world coordinates
bool = b2.Body:isBullet()
bool : if body is set to behave bullet
bool = b2.Body:isFixedRotation()
bool : if body has fixed rotation set
bool = b2.Body:isSleepingAllowed()
bool : if body is allowed to sleep
b2.Body:setBullet(flag)
flag : (bool)
b2.Body:setFixedRotation(flag)
flag : (bool)
b2.Body:setSleepingAllowed(flag)
flag : (bool)
ball:setPosition(x,y)
--get radius
local radius=ball:getWidth()/2
Parameters:
centerx : (number, optional) the x coordinate of the center
centery : (number, optional) the y coordinate of the center
radius : (number, optional) the radius
Results:
any : A new `b2.CircleShape` object.
any : A new `b2.CircleShape` object.
world:addEventListener(Event.END_CONTACT, function(e)
local manifold=e.contact:getWorldManifold()
if manifold.normal.y < 0.1 then
--collision ended from bottom
isTouchingGround=false
end
end)
Example:
local debugDraw=b2.DebugDraw.new()
world:setDebugDraw(debugDraw)
stage:addChild(debugDraw)
Example:
local debugDraw=b2.DebugDraw.new()
debugDraw:setFlags(b2.DebugDraw.SHAPE_BIT b2.DebugDraw.JOINT_BIT)
Distance joint
local jointDef=b2.createDistanceJointDef(body1, body2, 100, 100, 200, 100)
local distanceJoint=world:createJoint(jointDef)
--by default length between two bodies is the length they have between them when joint was
created
--but it is possilbe to change it using
distanceJoint:setLength(200)
distanceJoint:setDampingRatio(0.5)
distanceJoint:setFrequency(4)
-- ball
local body=world:createBody{type=b2.DYNAMIC_BODY}
local circle=b2.CircleShape.new(0, 0, radius)
local fixture=body:createFixture{shape=circle, density=1.0,
friction=0.1, restitution=0.2}
-- ball will collide with other ball and wall
fixture:setFilterData({categoryBits=BALL_MASK, maskBits=BALL_MASK+WALL_MASK, groupIndex=0})
local body=world:createBody{type=b2.DYNAMIC_BODY}
local poly=b2.PolygonShape.new()
poly:setAsBox(width, height)
local fixture=body:createFixture{shape=poly, density=1.0,
friction=0.1, restitution=0.2}
-- crate will collide with other crate and wall
fixture:setFilterData({categoryBits=CRATE_MASK, maskBits=CRATE_MASK+WALL_MASK, groupIndex=0})
local body=world:createBody{type=b2.STATIC_BODY}
local chain=b2.ChainShape.new()
chain:createLoop(
0,0,
application:getContentWidth(), 0,
application:getContentWidth(), application:getContentHeight(),
0, application:getContentHeight()
)
local fixture=body:createFixture{shape=chain, density=1.0,
friction=1, restitution=0.3}
-- walls will collide with both balls and crates
fixture:setFilterData({categoryBits=WALL_MASK, maskBits=CRATE_MASK+BALL_MASK, groupIndex=0})
-- ball
local body=world:createBody{type=b2.DYNAMIC_BODY}
local circle=b2.CircleShape.new(0, 0, radius)
local fixture=body:createFixture{shape=circle, density=1.0,
friction=0.1, restitution=0.2}
-- ball will collide with other ball and wall
fixture:setFilterData({categoryBits=BALL_MASK, maskBits=BALL_MASK+WALL_MASK, groupIndex=0})
local body=world:createBody{type=b2.DYNAMIC_BODY}
local poly=b2.PolygonShape.new()
poly:setAsBox(width, height)
local fixture=body:createFixture{shape=poly, density=1.0,
friction=0.1, restitution=0.2}
-- crate will collide with other crate and wall
fixture:setFilterData({categoryBits=CRATE_MASK, maskBits=CRATE_MASK+WALL_MASK, groupIndex=0})
local body=world:createBody{type=b2.STATIC_BODY}
local chain=b2.ChainShape.new()
chain:createLoop(
0,0,
application:getContentWidth(), 0,
application:getContentWidth(), application:getContentHeight(),
0, application:getContentHeight()
)
local fixture=body:createFixture{shape=chain, density=1.0,
friction=1, restitution=0.3}
-- walls will collide with both balls and crates
fixture:setFilterData({categoryBits=WALL_MASK, maskBits=CRATE_MASK+BALL_MASK, groupIndex=0})
Friction joint
--create empty box2d body for joint
local ground=world:createBody({})
ground:setPosition(350, 480)
Parameter:
inv_dt : (num)
Results:
num : x component of the reaction force on bodyB at the joint anchor in Newtons
num : y component of the reaction force on bodyB at the joint anchor in Newtons
Parameter:
inv_dt : (num)
Result:
Mouse joint
--create empty box2d body for joint
local ground=world:createBody({})
ps1:createParticleGroup({shape=shape2,
position={x=500,y=250},
color=0xFF0000,
alpha=1,
flags=0
})
ps1:createParticleGroup({shape=shape1,
position={x=400,y=50},
color=0x0000FF,
alpha=1,
flags=0
})
-- step the world and then update the position and rotation of sprites
local function onEnterFrame()
world:step(1/60, 8, 3)
end
stage:addEventListener(Event.ENTER_FRAME, onEnterFrame)
Parameter:
id : (num) Particle id
Result:
bool : True if the particle is within the particle system else false.
Parameter:
particleDef : (table) table with particle data
Example:
local polygonShape=b2.PolygonShape.new()
polygonShape:set(1,4, 2,6, 3,7)
Prismatic joint
--create empty box2d body for joint
local ground=world:createBody({})
ground:setPosition(465, 480)
Parameter:
inv_dt : (num)
Result:
num : The current motor force given the inverse time step, usually in N
Pulley joint
--create empty box2d body for joint
local ground=world:createBody({})
Revolute joint
--create empty box2d body for joint
local ground=world:createBody({})
ground:setPosition(300, 480)
Parameter:
inv_dt : (num)
Result:
num : The current motor torque given the inverse time step. Unit is N*m
Weld joint
local jointDef=b2.createWeldJointDef(body1, body2, 100, 100, 130, 100)
local weldJoint=world:createJoint(jointDef)
Wheel joint
--create empty box2d body for joint
local ground=world:createBody({})
ground:setPosition(350, 480)
ball:setPosition(100,100)
--get radius
local radius=ball:getWidth()/2
--add to scene
stage:addChild(ball)
stage:addEventListener(Event.ENTER_FRAME, function()
-- edit the step values if required. These are good defaults!
world:step(1/60, 8, 3)
ball:setPosition(ball.body:getPosition())
ball:setRotation(math.rad(ball.body:getAngle()))
end)
Parameters:
gravityx : (num) the x component the gravity
gravityy : (num) the y component the gravity
doSleep : (boolean, default = true) improve performance by not simulating inactive bodies
Results:
any : A new `b2.World` object.
any : A new `b2.World` object.
Parameter:
bodyDef : (table)
Result:
b2.Body : created body.
Example:
local body=world:createBody{
type=b2.STATIC_BODY,
position={x=0, y=0.5},
angle=math.pi/4,
linearVelocity={x=0.1, y=0.2},
}
Parameter:
jointDef : (table)
Result:
b2.Joint : created joint
Parameter:
particleSysDef : (table) parameters that define particle system
Result:
b2.ParticleSystem : new particle system
Parameters:
minx : (num) the minimal x coordinate of the query box
miny : (num) the minimal y coordinate of the query box
maxx : (num) the maximal x coordinate of the query box
maxy : (num) the maximal y coordinate of the query box
Result:
table : Indexed array of fixtures that potentially overlaps the provided AABB
end
Example:
local debugDraw=b2.DebugDraw.new()
world:setDebugDraw(debugDraw)
stage:addChild(debugDraw)
ball:setPosition(100,100)
--get radius
local radius=ball:getWidth()/2
--add to scene
stage:addChild(ball)
stage:addEventListener(Event.ENTER_FRAME, function()
-- edit the step values if required. These are good defaults!
world:step(1/60, 8, 3)
ball:setPosition(ball.body:getPosition())
ball:setRotation(math.rad(ball.body:getAngle()))
end)
world:addEventListener(Event.END_CONTACT, function(e)
local manifold=e.contact:getWorldManifold()
if manifold.normal.y < 0.1 then
--collision ended from bottom
isTouchingGround=false
end
end)
assert 2011.6+
Issues an error when the value of its argument v is false (i.e., nil or false); otherwise, returns all its
arguments. message is an error message; when absent, it defaults to "assertion failed!"
assert(v [, message])
v : (any) expression/function to assert
message : (str) error message if assert fails
collectgarbage 2011.6+
This function is a generic interface to the garbage collector. It performs different functions according to its first
argument, opt: <ul><li>"stop": stops the garbage collector. </li><li>"restart": restarts the garbage collector.
</li><li>"collect": performs a full garbage-collection cycle. </li><li>"count": returns the total memory in use by
Lua (in Kbytes). </li><li>"step": performs a garbage-collection step. The step "size" is controlled by arg (larger
values mean more steps) in a non-specified way. If you want to control the step size you must experimentally
tune the value of arg. Returns true if the step finished a collection cycle. </li><li>"setpause": sets arg as the
new value for the pause of the collector. Returns the previous value for pause. </li><li>"setstepmul": sets arg
as the new value for the step multiplier of the collector. Returns the previous value for step.</li></ul>
collectgarbage(opt [, arg])
opt : (str) command for garbage collector mechanism
arg : (varies) additional parameters for command
dofile 2011.6+
Opens the named file and executes its contents as a Lua chunk. When called without arguments, dofile
executes the contents of the standard input (stdin). Returns all values returned by the chunk. In case of
errors, dofile propagates the error to its caller (that is, dofile does not run in protected mode).
dofile(filename)
filename : (str) file to execute
error 2011.6+
Terminates the last protected function called and returns message as the error message. Function error
never returns. Usually, error adds some information about the error position at the beginning of the message.
The level argument specifies how to get the error position. With level 1 (the default), the error position is
where the error function was called. Level 2 points the error to where the function that called error was called;
and so on. Passing a level 0 avoids the addition of error position information to the message.
error(message [, level])
message : (str) error message
level : (num) the call stack level
getfenv 2011.6+
Returns the current environment in use by the function. f can be a Lua function or a number that specifies the
function at that stack level: Level 1 is the function calling getfenv. If the given function is not a Lua function, or
if f is 0, getfenv returns the global environment. The default for f is 1.
Parameter:
f : (varies) function or number(call stack level)
Result:
table : environment with all the defined values in environment scope
getmetatable 2011.6+
If object does not have a metatable, returns nil. Otherwise, if the object's metatable has a "__metatable" field,
returns the associated value. Otherwise, returns the metatable of the given object.
table = getmetatable(object)
Parameter:
object : (object) Object from which to get metatable
Result:
table : metatable
ipairs 2011.6+
Returns three values: an iterator function, the table t, and 0, so that the construction `for i,v in ipairs(t) do
body end` will iterate over the pairs (1,t[1]), (2,t[2]), ···, up to the first integer key absent from the table.
function, table, any = ipairs(t)
Parameter:
t : (table) indexed table to iterate through
Results:
function : iterator function
table : provided table t
any : value 0
loadfile 2011.6+
Loads a chunk from the file without execution. If there are no errors, returns the compiled chunk as a
function; otherwise, returns nil plus the error message. The environment of the returned function is the global
environment.
function = loadfile(filename)
Parameter:
filename : (str) name of the file to load
Result:
function : compiled chunk as a function; otherwise, returns nil
loadstring 2011.6+
Gets the chunk from the given string. To load and run a given string, use the idiom
`assert(loadstring(s))()`Chunkname is used as the chunk name for error messages and debug information.
When absent, chunkname defaults to the given string.
function = loadstring(str [, chunkname])
Parameters:
string : (str) string to load and compile
Result:
function : compiled chunk as a function; otherwise, returns nil
next 2011.6+
Allows a program to traverse all fields of a table. Its first argument is a table and its second argument is an
index in this table. next returns the next index of the table and its associated value. When called with nil as its
second argument, next returns an initial index and its associated value. When called with the last index, or
with nil in an empty table, next returns nil. If the second argument is absent, then it is interpreted as nil. In
particular, you can use next(t) to check whether a table is empty. The order in which the indices are
enumerated is not specified, even for numeric indices. (To traverse a table in numeric order, use a numerical
for or the `ipairs` function.) The behavior of next is undefined if, during the traversal, you assign any value to
a non-existent field in the table. You may however modify existing fields. In particular, you may clear existing
fields.
next(table [, index])
table : (table) table to traverse
index : (num) previous table index
pairs 2011.6+
Returns three values: an iterator function, the table t, and nil, so that the construction for i,v in pairs(t) do
body end will iterate over any key pairs (indexed or associative) even with nil values
function, table, nil = pairs(t)
Parameter:
t : (table) table to iterate
Results:
function : iterator function
table : provided table
nil : nil value
pcall 2011.6+
Calls function f with the given arguments in protected mode. This means that any error inside f is not
propagated; instead, `pcall` catches the error and returns a status code. Its first result is the status code (a
boolean), which is true if the call succeeds without errors. In such case, `pcall` also returns all results from
the call, after this first result. In case of any error, `pcall` returns false plus the error message.
bool, any = pcall(f [, arg1] [, arg2] [, ...])
Parameters:
f : (function) function to call in protected mode
arg1 : (any) argument to pass to the function
arg2 : (any) argument to pass to the function
... : (any) other optional arguments
Results:
bool : false if there was error, true if function call succeeded
any : all the results that function returns
print 2011.6+
rawequal 2011.6+
Checks whether v1 is equal to v2, without invoking any metamethod. Returns a boolean.
bool = rawequal(v1, v2)
Parameters:
v1 : (any) first value to compare
v2 : (any) second value to compare
Result:
bool : true if values are equal, or false if different
rawget 2011.6+
Gets the real value of table[index], without invoking any metamethod. table must be a table; index may be
any value.
any = rawget(table, key)
Parameters:
table : (table) table to get value from
key : (any) key value in the table
Result:
any : value from the table
rawset 2011.6+
Sets the real value of table[index] to value, without invoking any metamethod. table must be a table, index
any value different from nil, and value any Lua value. This function returns table.
table = rawset(table, key, value)
Parameters:
table : (table) table to set the value to
key : (any) key of the table to set the value to
value : (any) value to store in the table
Result:
table : provided table
require 2011.6+
Loads and runs libraries. Roughly, `require` does the same job as `dofile`, but, `require` searches for the file
in a path. Because of that, `require` is the preferred function in Lua for loading libraries.
require(packagename)
packagename : (str) library to load
Parameters:
f : (varies) function or number(call stack level)
table : (table) environment table to set
Result:
varies : returns provided function or nil
setmetatable 2011.6+
Sets the `metatable` for the given table. (You cannot change the `metatable` of other types from Lua, only
from C.) If `metatable` is nil, removes the `metatable` of the given table. If the original `metatable` has a
"__metatable" field, raises an error. This function returns table.
table = setmetatable(table, metatable)
Parameters:
table : (table) table to set metatable to
metatable : (varies) value to use as metatable
Result:
table : provided table
tonumber 2011.6+
Tries to convert its argument to a number. If the argument is already a number or a string convertible to a
number, then tonumber returns this number; otherwise, it returns nil. An optional argument specifies the
base to interpret the numeral. The base may be any integer between 2 and 36, inclusive. In bases above 10,
the letter 'A' (in either upper or lower case) represents 10, 'B' represents 11, and so forth, with 'Z' representing
35. In base 10 (the default), the number can have a decimal part, as well as an optional exponent part. In
other bases, only unsigned integers are accepted.
num = tonumber(e [, base])
Parameters:
e : (any) value to convert to number
base : (varies) the base to convert number to, default: 10
Result:
num : returns the number or nil if it could not be converted
tostring 2011.6+
Receives an argument of any type and converts it to a string in a reasonable format. For complete control of
how numbers are converted, use string.format. If the `metatable` of e has a "__tostring" field, then `tostring`
calls the corresponding value with e as argument, and uses the result of the call as its result.
str = tostring(e)
Parameter:
e : (any) value to convert to string
type 2011.6+
Returns the type of its only argument, coded as a string. The possible results of this function are "nil" (a
string, not the value nil), "number", "string", "boolean", "table", "function", "thread", and "userdata".
str = type(v)
Parameter:
v : (any) value to get type from
Result:
str : type of the variable
unpack 2011.6+
Returns the elements from the given table. This function is equivalent to return list[i], list[i+1], ···, list[j]
except that the above code can be written only for a fixed number of elements. By default, i is 1 and j is the
length of the list, as defined by the length operator.
multiple = unpack(list)
Parameter:
list : (table) table from which to extract elements
Result:
multiple : all values from table as separate values
xpcall 2011.6+
`pcall` function f with new error handler err.The operations related to coroutines comprise a sub-library of the
basic library and come inside the table coroutine.
xpcall(f, err)
f : (function) pcall function
err : (str) error message
--[[ We create a coroutine using the coroutine.create(fn) function. We pass it an entry point for
the thread which is a Lua function. The object returned by Lua is a thread: ]]
--[[ We can find out what state the thread is in using the coroutine.status() function, e.g., ]]
print(coroutine.status(co)) --suspended
--[[ The state suspended means that the thread is alive, and as you would expect, not doing
anything. Note that when we created the thread it did not start executing. To start the thread we
use the coroutine.resume() function. Lua will enter the thread and leave when the thread yields.
]]
coroutine.resume(co) -- prints foo 1
--[[ The coroutine.resume() function returns the error status of the resume call. The output
acknowledges that we entered the function foo and then exited with no errors. Now is the
interesting bit. With a function we would not be able to carry on where we left off, but with
coroutines we can resume again: ]]
coroutine.resume(co) -- prints foo 2
--[[ We can see we executed the line after the yield in foo and again returned without error.
However, if we look at the status we can see that we exited the function foo and the coroutine
terminated. ]]
print(coroutine.status(co)) --prints dead
--[[ If we try to resume again a pair of values is returned: an error flag and an error message:
]]
print(coroutine.resume(co)) -- prints false cannot resume dead coroutine
Parameter:
f : (function) lua function
Parameters:
co : (coroutine) coroutine to start or resume
val1 : (any) value to pass as the result
... : (any) other optional values to pass as results
Results:
bool : true if coroutine ran without errors, false otherwise
multiple : values provided to coroutine.yield function call
Parameter:
co : (coroutine) coroutine to check status for
Result:
str : the state of coroutine
Parameter:
f : (function) lua function
Result:
function : function that resumes coroutine every time it is called, behaving similar to coroutine.resume
Parameters:
function : (any) function or call stack level
what : (str) what information to return
Result:
table : table with information about the function
Parameters:
level : (num) level of the scope/stack
local : (num) index of the function
Results:
str : name of the variable
varies : value of the variable
Parameters:
func : (function) function to look for upvalue
up : (num) index of the upvalue
Results:
str : the name of upvalue
varies : the value of upvalue
Parameters:
level : (num) level of the stack
Result:
str : name of the variable or nil
Parameters:
func : (function) function to set the upvalue for
up : (num) index of the upvalue
value : (varies) value to set as upvalue
Result:
str : name of the upvalue or nil
Parameters:
message : (str) message to debug
level : (num) stack level
Result:
str : debug traceback
Copy a file
local function copy(src, dst)
local srcf=io.open(src, "rb")
local dstf=io.open(dst, "wb")
local size=2^13 -- good buffer size (8K)
while true do
local block=srcf:read(size)
if not block then break end
dstf:write(block)
end
srcf:close()
dstf:close()
end
Parameters:
format1 : (str) format
Result:
str : read string from file
Parameters:
whence : (str) setting the base point for offset
offset : (num) offset to set position to
Result:
num : the position in file measured in bytes from the beginning of the file
Copy a file
local function copy(src, dst)
local srcf=io.open(src, "rb")
local dstf=io.open(dst, "wb")
local size=2^13 -- good buffer size (8K)
while true do
local block=srcf:read(size)
if not block then break end
dstf:write(block)
end
srcf:close()
dstf:close()
end
io . close 2011.6+
Equivalent to `file:close`. Without a file, closes the default output file.
io.close([file])
file : (file) file object to close
io . flush 2011.6+
Equivalent to file:flush over the default output file.
io.flush()
io . input 2011.6+
When called with a file name, it opens the named file (in text mode), and sets its handle as the default input
file. When called with a file handle, it simply sets this file handle as the default input file. When called without
parameters, it returns the current default input file. In case of errors this function raises the error, instead of
returning an error code.
file = io.input([file])
Parameter:
file : (file) file object to use as default input
Result:
file : default input file object
io . lines 2011.6+
Opens the given file name in read mode and returns an iterator function that, each time it is called, returns a
new line from the file. Therefore, the construction `for line in io.lines(filename) do body end` will iterate
over all lines of the file. When the iterator function detects the end of file, it returns nil (to finish the loop) and
automatically closes the file. The call io.lines() (with no file name) is equivalent to io.input():lines(); that is, it
iterates over the lines of the default input file. In this case it does not close the file when the loop ends.
function = io.lines([filename])
Result:
function : iterator function
io . open 2011.6+
This function opens a file, in the mode specified in the string mode. It returns a new file handle, or, in case of
errors, nil plus an error message. The mode string can be any of the following: "r": read mode (the
default);"w": write mode;"a": append mode;"r+": update mode, all previous data is preserved;"w+": update
mode, all previous data is erased;"a+": append update mode, previous data is preserved, writing is only
allowed at the end of file. The mode string can also have a 'b' at the end, which is needed in some systems to
open the file in binary mode. This string is exactly what is used in the standard C function fopen.
file = io.open(filename [, mode])
Parameters:
filename : (str) filename to open
mode : (str) mode in which to open the file
Result:
file : file object
io . output 2011.6+
When called with a file name, it opens the named file (in text mode), and sets its handle as the default output
file. When called with a file handle, it simply sets this file handle as the default output file. When called without
parameters, it returns the current default output file. In case of errors this function raises the error, instead of
returning an error code.
file = io.output([file])
Parameter:
file : (file) file object to use as default output
Result:
file : default output file object
io . read 2011.6+
Reading from default input, basically equivalent to io.input():read
str = io.read(format1 [, ...])
Parameters:
format1 : (str) reading format
... : (str) more optional formats
Result:
str : returns read values or nil
io . tmpfile 2011.6+
Returns a handle for a temporary file. This file is opened in update mode and it is automatically removed
when the program ends.
file = io.tmpfile()
file : file object for temporary file
Parameter:
obj : (any) object to test
Result:
str : string representing the state of the object or nil if not file handler
io . write 2011.6+
Writes value to default output, basically equivalent to io.output():write.
io.write(value1 [, ...])
value1 : (str) value to write
... : (multiple) other optional values to write
Parameter:
v : (num) number to use for absolute value
Result:
num : absolute value of v
Parameter:
v : (num) value to get acos from
Result:
num : acos value of provided value
Parameter:
v : (num) value to get asin from
Result:
num : asin value from v
Parameter:
v : (num) value to get atan from
Result:
num : atan value of v
Parameters:
Result:
num : result
Parameter:
v : (num) value to ceil
Result:
num : ceiled value
Parameter:
rad : (num) angle in radians
Result:
num : result
Parameter:
rad : (num) radian value to convert to degree
Result:
num : result in degree
Parameter:
v : (num) level of exponentiation for e
Result:
num : result of exponentiation
Parameter:
Result:
num : floored value
Parameters:
v1 : (num) first value
v2 : (num) second value
Result:
num : remainder of division
Parameter:
v : (num) value
Result:
num : result
Parameters:
v1 : (num) first value
v2 : (num) second value
Result:
num : result
Parameter:
v : (num) value
Result:
num : result
Parameter:
v : (num) value
Result:
num : result
Parameters:
v1 : (num) first value
... : (multiple) more optional numbers
Result:
num : highest number of all provided numbers
Parameters:
v1 : (num) firs value
... : (multiple) more optional numbers
Result:
num : smallest number of all provided numbers
Parameters:
v1 : (num) value to exponentiate
v2 : (num) power in which to exponentiate
Result:
num : result of exponentiation
Parameter:
deg : (num) angle in degrees
Result:
num : angle in radians
Parameters:
n : (num) upper limit if only n provided, lower limit if u also provided
u : (num) upper limit
Result:
num : pseudo random number
Parameter:
rad : (num) angle in radians
Result:
num : sine of provided angle
Parameter:
v : (num) value to compute the square root for
Result:
num : square root
Parameter:
rad : (num) angle in radians
Result:
num : tangent of the angle
os . clock 2011.6+
returns CPU time used by program in seconds
num = os.clock()
num : time in seconds
os . date 2011.6+
Returns a string or a table containing 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(format [, time])
format : (str) format of the date
time : (num) time to format
os . difftime 2011.6+
returns number of seconds from time t1 to time t2
num = os.difftime(t2, t1)
Parameters:
t2 : (num) first time
t1 : (num) second time
Result:
num : different between time dates in seconds
os . execute 2011.6+
This function is equivalent to the C function system. It passes command to be executed by an operating
system shell. It returns a status code, which is system-dependent. If command is absent, then it returns
nonzero if a shell is available and zero otherwise.
num = os.execute(command)
Parameter:
command : (str) command to execute
Result:
num : status code
os . exit 2011.6+
Calls the C function exit, with an optional code, to terminate the host program. The default value for code is
os . getenv 2011.6+
Returns the value of the process environment variable varname, or nil if the variable is not defined.
any = os.getenv(varname)
Parameter:
varname : (str) name of the variable
Result:
any : value of the variable
os . remove 2011.6+
Deletes the file or directory with the given name. Directories must be empty to be removed. If this function
fails, it returns nil, plus a string describing the error.
os.remove(filename)
filename : (str) filename to delete
os . rename 2011.6+
Renames file or directory named oldname to newname. If this function fails, it returns nil, plus a string
describing the error.
os.rename(oldname, newname)
oldname : (str) current name of the file
newname : (str) new name of the file
os . setlocale 2011.6+
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.
str = os.setlocale(locale [, category])
Parameters:
locale : (str) locale to set
category : (str) category to change
Result:
str : name if current locale
os . time 2011.6+
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
Parameter:
table : (table) table representing a date time
Result:
num : time in seconds
os . timer 2011.6+
Returns precise time in seconds relative to some arbitrary point.
num = os.timer()
num : Precise time in seconds relative to some arbitrary point
os . tmpname 2011.6+
Returns a string with a file name that can be used for a temporary file. The file must be explicitly opened
before its use and explicitly removed when no longer needed. On some systems (POSIX), this function also
creates a file with that name, to avoid security risks. (Someone else might create the file with wrong
permissions in the time between getting the name and creating the file.) You still have to open the file to use
it and to remove it (even if you do not use it). When possible, you may prefer to use `io.tmpfile`, which
automatically removes the file when the program ends.
str = os.tmpname()
str : name for the temporary file
Parameters:
s : (str) string to get numerical codes from
i : (num) start symbol (default = 1)
j : (num) end symbol (defaults = i)
Result:
numbers : numerical codes of characters in provided range
Parameters:
i1 : (num) first character represented by numerical code
i2 : (num) second character represented by numerical code
... : (multiple) more optional characters represented by numerical codes
Result:
str : string created from characters
Parameter:
function : (function) function to convert to string
Result:
str : string representation of function
Parameters:
s : (str) string where to find a pattern
pattern : (str) pattern to find
init : (num) index where to start searching for pattern
plain : (bool) if true, then it simply matches substring without any special symbols (default = false)
Result:
numbers : indexes of occurrence of the pattern or nil
Parameters:
s : (str) string where to look for patterns
pat : (str) pattern to look for
Result:
function : iterator function
Parameters:
s : (str) string where to make replacements
pat : (str) pattern what to replace
repl : (varies) to what to replace
n : (num) number of replacements
Result:
str : modified string with replacements
Parameter:
s : (str) string for which to measure length
Result:
num : the length of the string
Parameter:
s : (str) string to modify
Result:
str : lowercased string
Parameters:
string : (str) Any string.
pattern : (str) Specifies the pattern to match.
Result:
str : String matching pattern.
Parameters:
s : (str) string to copy
n : (num) how many times to copy a string
Result:
str : concatenated by n copies
Parameters:
s : (str) string to get substring from
i : (num) start index of substring
j : (num) index of the last character of substring
Result:
str : substring
Parameter:
s : (str) string to modify
Result:
str : uppercased string
Parameters:
table : (table) table of values to concatenate
sep : (str) separator what to insert between table elements
i : (num) concatenate from this element (default is 1)
j : (num) concatenate until this element (default is table length)
Result:
str : concatenated string
Parameters:
table : (table) table from which to remove element
pos : (num) index at which to remove element (default is last element)
Result:
varies : removed value
Parameters:
s : (str)
i : (num) default is 1
j : (num)
Result:
numbers : Returns the internal numerical codes of the characters
Parameters:
code1 : (num)
code2 : (num)
codeN : (num)
Result:
str : string with provided characters
Parameters:
s : (str)
charpos : (num)
offset : (num)
Result:
num : return byte offset of this UTF-8 char index
Result:
numbers : Returns the codepoints (as integers) from all characters in s
Parameter:
s : (str)
Result:
iterator
Parameter:
s : (str)
Result:
str : escaped string
Parameters:
s : (str)
pattern : (str)
init : (num)
plain : (bool)
Result:
numbers : the indices of s where this occurrence starts and ends; otherwise, it returns nil
Parameter:
s : (str)
Result:
str : folded case string
Parameters:
s : (str)
pattern : (str)
Result:
function : iterator function
Parameters:
s : (str)
pattern : (str)
repl : (varies)
n : (num)
Results:
str : replaced string
num : number of substitutions
Parameters:
s : (str)
idx : (num) index where to insert
substring : (str)
Result:
str : new string
Parameters:
s : (str)
i : (num)
j : (num)
Result:
num : number of characters
Parameter:
s : (str)
Result:
str : lowercased string
Parameters:
s : (str)
pattern : (str)
init : (num)
Result:
strings : captures
Parameters:
a : (str)
b : (str)
Result:
num : compare state
Parameters:
s : (str)
charpos : (num)
offset : (num)
Result:
varies : next iteration
Parameters:
s : (str)
n : (num)
i : (num)
Result:
num : position (in bytes)
Parameter:
s : (str)
Result:
str : reversed string
Parameters:
s : (str)
i : (num)
j : (num)
Result:
str : substring of s that starts at i and continues until j
Parameter:
s : (str)
Result:
str : string in title case
Parameter:
s : (str)
Result:
str : string in upper case
Parameters:
s : (str)
ambi_is_double : (bool)
default_width : (num)
Result:
num : width
Parameters:
s : (str)
location : (num)
ambi_is_double : (bool)
default_width : (num)
Result:
num : character index at given location
Parameters:
adler32 : (num) adler value
buffer : (str) buffer to modify value for
Result:
str : without parameters returns initial value
Parameters:
buffer : (str) string to compress
level : (num) compression level, 0 no compression, 9 best compression, -1 default compression
method : (num) compression method, should be 8 for this version
windowBits : (num) from 8 to 15, larger values of this parameter result in better compression at the expense
of memory usage
memLevel : (num) 1 uses minimum memory but is slow and reduces compression ratio; 9 uses maximum
memory for optimal speed
strategy : (num) 1 - Filtered, 2 - Huffman, 3 - RLE, 4 - Fixed, 0 - default
Result:
str : compressed string
Parameters:
crc32 : (num) crc32 value
buffer : (str) buffer to modify value
Result:
str : without parameters returns initial value
Parameters:
sink : (function or table) function | { write: function [, close: function, flush: function ] },
level : (num) compression level, 0 no compression, 9 best compression, -1 default compression
method : (num) compression method, should be 8 for this version
windowBits : (num) from 8 to 15, larger values of this parameter result in better compression at the expense
of memory usage
memLevel : (num) 1 uses minimum memory but is slow and reduces compression ratio; 9 uses maximum
memory for optimal speed
strategy : (num) 1 - Filtered, 2 - Huffman, 3 - RLE, 4 - Fixed, 0 - default
dictionary : (str) compression dictionary
Result:
stream : deflate stream
Parameters:
source : (many) string | function | { read: function, close: function }
windowBits : (num) from 8 to 15, larger values of this parameter result in better compression at the expense
of memory usage
dictionary : (str) compression dictionary
Result:
stream : inflate stream
--initialize amazon
amazon=Ads.new("amazon")
amazon:setKey("amazon-key")
--initialize admob
admob=Ads.new("admob")
admob:setKey("admob-key")
Parameter:
property : (str) value for which property to get
Result:
varies : value of the property
Parameters:
x : (num) number to shift
n : (num) amount of bits to shift
Result:
num : bitwise arithmetic right-shift
Parameters:
x1 : (num) first number for and operation
x2 : (num) second and more numbers can be provided for and operation
Result:
num : bitwise and
Parameter:
x : (num) number to which to apply bitwise not
Result:
num : bitwise not
Parameters:
x1 : (num) first number for or operation
x2 : (num) second and more numbers can be provided for or operation
Result:
num : bitwise or
Parameter:
x : (num) number to swap
Result:
num : Swapped bytes
Parameters:
x1 : (num) first number for xor operation
x2 : (num) second and more numbers can be provided for xor operation
Result:
num : bitwise xor
Parameters:
x : (num) number to shift
n : (num) amount of bits to shift
Result:
num : bitwise logical left-shift
Parameters:
x : (num) number to rotate
n : (num) amount of bits to rotate
Result:
num : bitwise left rotation
Parameters:
x : (num) number to rotate
n : (num) amount of bits to rotate
Result:
Parameters:
x : (num) number to shift
n : (num) amount of bits to shift
Result:
num : bitwise logical right-shift
Parameter:
x : (num) number which range to normalize
Result:
num : normalized number
Parameters:
x : (num) number to convert to hex string
n : (num) number of hex digits to convert
Result:
str : hex string
Example:
require "camera"
application:setLogicalDimensions(ch,cw)
local b=Bitmap.new(Camera.texture)
stage:addChild(b)
Parameters:
texture : (Texture) The texture to render camera stream into
device : (str) The camera to use or nil to use the default one
Results:
num : Nominal width of camera images
num : Nominal height of camera images
controller:addEventListener(Event.KEY_DOWN, function(e)
print("Button Down ", e.playerId, e.keyCode, findKeyCode(e.keyCode))
end)
controller:addEventListener(Event.KEY_UP, function(e)
print("Button Up ", e.playerId, e.keyCode, findKeyCode(e.keyCode))
end)
controller:addEventListener(Event.RIGHT_JOYSTICK, function(e)
print("Player: ", e.playerId)
print("RIGHT_JOYSTICK:", "x:"..e.x, "y:"..e.y, "angle:"..e.angle, "strength:"..e.strength)
end)
controller:addEventListener(Event.LEFT_JOYSTICK, function(e)
print("Player: ", e.playerId)
print("LEFT_JOYSTICK:", "x:"..e.x, "y:"..e.y, "angle:"..e.angle, "strength:"..e.strength)
end)
controller:addEventListener(Event.RIGHT_TRIGGER, function(e)
print("Player: ", e.playerId)
print("RIGHT_TRIGGER:", "strength:"..e.strength)
end)
controller:addEventListener(Event.LEFT_TRIGGER, function(e)
print("Player: ", e.playerId)
print("LEFT_TRIGGER:", "strength:"..e.strength)
end)
controller:addEventListener(Event.CONNECTED, function(e)
print("Player: ", e.playerId, "connected")
print("Are there any controllers?", controller:isAnyAvailable())
print("Controller count", controller:getPlayerCount())
print("Name of controller "..e.playerId, controller:getControllerName(e.playerId))
print("players", #controller:getPlayers())
end)
controller:addEventListener(Event.DISCONNECTED, function(e)
print("Player: ", e.playerId, "disconnected")
end)
Parameter:
id : (num) controller id
Result:
str : controller name
Example:
flurry.logEvent('myEvent1')
flurry.logEvent('myEvent2', {key='value'})
flurry.logEvent('myEvent3', {key='value'}, true)
Parameter:
productType : (string, optional) The item type. It can be GoogleBilling.INAPP or GoogleBilling.SUBS.
Result:
bool : `true` if in-app billing service is available, `false` otherwise.
Parameter:
notificationId : (str)
Result:
bool : `true` if in-app billing service is available, `false` otherwise.
Parameters:
productId : (str)
productType : (string, optional)
developerPayload : (string, optional)
Result:
bool : `true` if in-app billing service is available, `false` otherwise.
Example:
-- if the platform is iOS, load the iAd module
if application:getDeviceInfo() == 'iOS' then
require 'iad'
end
-- if iAd module is loaded and iAd framework is available, create an ad banner and then show it
local banner=nil
if iad and iad.isAvailable() then
banner=iad.Banner.new(iad.Banner.TOP, iad.Banner.PORTRAIT)
banner:addEventListener(Event.BANNER_AD_LOADED, onBannerAdLoaded)
banner:addEventListener(Event.BANNER_AD_FAILED, onBannerAdFailed)
banner:addEventListener(Event.BANNER_ACTION_BEGIN, onBannerActionBegin)
banner:addEventListener(Event.BANNER_ACTION_FINISHED, onBannerActionFinished)
banner:show() -- show it because newly created banners are not visible by default
end
Create new notification and dispatch after one hour with repeating period of one day
local note=Notification.new(2)
note:setTitle("Notification app")
note:setMessage("I will bother you each day")
note:dispatchAfter({hour=1}, {day=1})
--check if id is in it
if t[id] then
--notification is still scheduled
--let's modify it by creating new instance with same id
local note=Notification.new(id)
note:setTitle("New title")
note:setMessage("New message")
--if we want to modify dispatch time we need to redispatch it
note:dispatchAfter({day=1})
end
--check if id is in it
if t[id] then
--notification is still scheduled
--let's modify it by creating new instance with same id
local note=Notification.new(id)
note:setTitle("New title")
note:setMessage("New message")
--if we want to modify dispatch time we need to redispatch it
note:dispatchAfter({day=1})
end
--check if id is in it
if t[id] then
--notification is still scheduled
end
Catching event if app opened from local notification or notification received in background
--retrieve shared instance
local mngr=NotificationManager.getSharedInstance()
mngr:addEventListener(Event.LOCAL_NOTIFICATION, function(e)
--getting id of notification
local id=e.id
Cancel notification