Sei sulla pagina 1di 270

Gideros API Reference

www.GiderosMobile.com
Gideros API Contributors
Contents

Lua Enhancements .......................................................................................................................................................... 1


Better and easier syntax for arrays ............................................................................................................................ 1
Binary Numbers ......................................................................................................................................................... 1
Bitwise Operators....................................................................................................................................................... 1
Integer Divide Operator.............................................................................................................................................. 2
Larger and Smaller Operators ................................................................................................................................... 2
Macro Constants........................................................................................................................................................ 2
Macro Functions ........................................................................................................................................................ 3
Mutation Operators .................................................................................................................................................... 4
Octal Numbers ........................................................................................................................................................... 4
Trigonometry Conversion Operators.......................................................................................................................... 4
Universal Bytecode .................................................................................................................................................... 4
Main API ............................................................................................................................................................................ 5
Accelerometer............................................................................................................................................................ 6
isAvailable.......................................................................................................................................................... 6
new .................................................................................................................................................................... 6
getAcceleration .................................................................................................................................................. 6
start.................................................................................................................................................................... 6
stop .................................................................................................................................................................... 6
AlertDialog ................................................................................................................................................................. 7
new .................................................................................................................................................................... 7
hide .................................................................................................................................................................... 7
show .................................................................................................................................................................. 7
Application ................................................................................................................................................................. 8
canOpenUrl........................................................................................................................................................ 8
configureFrustum............................................................................................................................................... 8
exit ..................................................................................................................................................................... 8
getApiVersion .................................................................................................................................................... 8
getAppId ............................................................................................................................................................ 8
getBackgroundColor .......................................................................................................................................... 9
getContentHeight............................................................................................................................................... 9
getContentWidth ................................................................................................................................................ 9
getDeviceHeight ................................................................................................................................................ 9
getDeviceInfo..................................................................................................................................................... 9
getDeviceOrientation ......................................................................................................................................... 9
getDeviceSafeArea.......................................................................................................................................... 10
getDeviceWidth................................................................................................................................................ 10
getFps.............................................................................................................................................................. 10
getLanguage.................................................................................................................................................... 10
getLocale ......................................................................................................................................................... 10
getLogicalBounds ............................................................................................................................................ 10
getLogicalHeight .............................................................................................................................................. 11
getLogicalScaleX ............................................................................................................................................. 11
getLogicalScaleY ............................................................................................................................................. 11
getLogicalTranslateX ....................................................................................................................................... 11
getLogicalTranslateY ....................................................................................................................................... 11
getLogicalWidth ............................................................................................................................................... 11
getOrientation .................................................................................................................................................. 11
getScaleMode.................................................................................................................................................. 11
getScreenDensity ............................................................................................................................................ 12
getTextureMemoryUsage ................................................................................................................................ 12
isPlayerMode ................................................................................................................................................... 12
openUrl ............................................................................................................................................................ 12
setBackgroundColor ........................................................................................................................................ 12
setFps .............................................................................................................................................................. 12
setFullScreen................................................................................................................................................... 13
setKeepAwake................................................................................................................................................. 13
setKeyboardVisibility........................................................................................................................................ 13
setLogicalDimensions...................................................................................................................................... 13
setOrientation .................................................................................................................................................. 13
setScaleMode .................................................................................................................................................. 14
setWindowSize ................................................................................................................................................ 14
vibrate .............................................................................................................................................................. 14
Bitmap...................................................................................................................................................................... 15
new .................................................................................................................................................................. 15
getAnchorPoint ................................................................................................................................................ 15
setAnchorPoint ................................................................................................................................................ 15
setTexture........................................................................................................................................................ 15
setTextureRegion ............................................................................................................................................ 15
Core ......................................................................................................................................................................... 17
asyncCall ......................................................................................................................................................... 17
class................................................................................................................................................................. 17
frameStatistics ................................................................................................................................................. 17
profilerReport ................................................................................................................................................... 17
profilerReset .................................................................................................................................................... 17
profilerStart ...................................................................................................................................................... 17
profilerStop ...................................................................................................................................................... 17
random............................................................................................................................................................. 18
randomSeed .................................................................................................................................................... 18
yield ................................................................................................................................................................. 18
Cryptography ........................................................................................................................................................... 19
aesDecrypt....................................................................................................................................................... 19
aesEncrypt....................................................................................................................................................... 19
md5.................................................................................................................................................................. 19
Event........................................................................................................................................................................ 20
new .................................................................................................................................................................. 20
getTarget ......................................................................................................................................................... 20
getType............................................................................................................................................................ 20
stopPropagation............................................................................................................................................... 20
EventDispatcher....................................................................................................................................................... 21
new .................................................................................................................................................................. 21
addEventListener............................................................................................................................................. 21
dispatchEvent .................................................................................................................................................. 22
hasEventListener ............................................................................................................................................. 22
removeEventListener....................................................................................................................................... 22
Font.......................................................................................................................................................................... 23
getDefault ........................................................................................................................................................ 23
new .................................................................................................................................................................. 23
FontBase.................................................................................................................................................................. 24
getAdvanceX ................................................................................................................................................... 24
getAscender..................................................................................................................................................... 24
getBounds........................................................................................................................................................ 24
getLineHeight................................................................................................................................................... 24
layoutText ........................................................................................................................................................ 24
Geolocation.............................................................................................................................................................. 26
getAccuracy ..................................................................................................................................................... 26
getThreshold.................................................................................................................................................... 26
isAvailable........................................................................................................................................................ 26
isHeadingAvailable .......................................................................................................................................... 26
new .................................................................................................................................................................. 26
setAccuracy ..................................................................................................................................................... 26
setThreshold .................................................................................................................................................... 27
start.................................................................................................................................................................. 27
startUpdatingHeading ...................................................................................................................................... 27
startUpdatingLocation...................................................................................................................................... 27
stop .................................................................................................................................................................. 27
stopUpdatingHeading ...................................................................................................................................... 27
stopUpdatingLocation ...................................................................................................................................... 27
Gyroscope................................................................................................................................................................ 28
isAvailable........................................................................................................................................................ 28
new .................................................................................................................................................................. 28
getRotationRate............................................................................................................................................... 28
start.................................................................................................................................................................. 28
stop .................................................................................................................................................................. 28
JS............................................................................................................................................................................. 30
eval .................................................................................................................................................................. 30
KeyCode .................................................................................................................................................................. 31
Matrix ....................................................................................................................................................................... 32
new .................................................................................................................................................................. 32
getAnchorPosition............................................................................................................................................ 32
getElements..................................................................................................................................................... 32
getM11............................................................................................................................................................. 32
getM12............................................................................................................................................................. 33
getM21............................................................................................................................................................. 33
getM22............................................................................................................................................................. 33
getMatrix .......................................................................................................................................................... 33
getPosition ....................................................................................................................................................... 33
getRotationX .................................................................................................................................................... 34
getRotationY .................................................................................................................................................... 34
getRotationZ .................................................................................................................................................... 34
getScale........................................................................................................................................................... 34
getScaleX ........................................................................................................................................................ 34
getScaleY ........................................................................................................................................................ 34
getScaleZ......................................................................................................................................................... 34
getTx................................................................................................................................................................ 34
getTy................................................................................................................................................................ 35
getTz................................................................................................................................................................ 35
getX ................................................................................................................................................................. 35
getY ................................................................................................................................................................. 35
getZ.................................................................................................................................................................. 35
invert ................................................................................................................................................................ 35
multiply............................................................................................................................................................. 35
orthographicProjection..................................................................................................................................... 35
perspectiveProjection ...................................................................................................................................... 36
rotate................................................................................................................................................................ 36
scale ................................................................................................................................................................ 37
setAnchorPosition............................................................................................................................................ 37
setElements ..................................................................................................................................................... 37
setM11 ............................................................................................................................................................. 37
setM12 ............................................................................................................................................................. 37
setM21 ............................................................................................................................................................. 37
setM22 ............................................................................................................................................................. 38
setMatrix .......................................................................................................................................................... 38
setPosition ....................................................................................................................................................... 38
setRotationX .................................................................................................................................................... 38
setRotationY .................................................................................................................................................... 38
setRotationZ .................................................................................................................................................... 39
setScale ........................................................................................................................................................... 39
setScaleX......................................................................................................................................................... 39
setScaleY......................................................................................................................................................... 39
setScaleZ......................................................................................................................................................... 39
setTx ................................................................................................................................................................ 39
setTy ................................................................................................................................................................ 39
setTz ................................................................................................................................................................ 39
setX.................................................................................................................................................................. 40
setY.................................................................................................................................................................. 40
setZ.................................................................................................................................................................. 40
transformPoint ................................................................................................................................................. 40
translate ........................................................................................................................................................... 40
Mesh ........................................................................................................................................................................ 41
new .................................................................................................................................................................. 41
clearColorArray................................................................................................................................................ 41
clearIndexArray................................................................................................................................................ 41
clearTexture..................................................................................................................................................... 41
clearTextureCoordinateArray........................................................................................................................... 41
clearVertexArray .............................................................................................................................................. 42
getColor ........................................................................................................................................................... 42
getColorArraySize............................................................................................................................................ 42
getIndex ........................................................................................................................................................... 42
getIndexArraySize ........................................................................................................................................... 42
getTextureCoordinate ...................................................................................................................................... 42
getTextureCoordinateArraySize ...................................................................................................................... 43
getVertex ......................................................................................................................................................... 43
getVertexArraySize.......................................................................................................................................... 43
resizeColorArray .............................................................................................................................................. 43
resizeIndexArray.............................................................................................................................................. 43
resizeTextureCoordinateArray ......................................................................................................................... 43
resizeVertexArray ............................................................................................................................................ 44
setColor ........................................................................................................................................................... 44
setColorArray................................................................................................................................................... 44
setColors.......................................................................................................................................................... 44
setGenericArray............................................................................................................................................... 45
setIndex ........................................................................................................................................................... 45
setIndexArray................................................................................................................................................... 45
setIndices......................................................................................................................................................... 46
setTexture........................................................................................................................................................ 46
setTextureCoordinate ...................................................................................................................................... 46
setTextureCoordinateArray.............................................................................................................................. 46
setTextureCoordinates .................................................................................................................................... 47
setVertex.......................................................................................................................................................... 47
setVertexArray ................................................................................................................................................. 47
setVertices ....................................................................................................................................................... 48
MovieClip ................................................................................................................................................................. 49
new .................................................................................................................................................................. 50
clearAction ....................................................................................................................................................... 50
gotoAndPlay .................................................................................................................................................... 50
gotoAndStop .................................................................................................................................................... 50
play .................................................................................................................................................................. 50
setGotoAction .................................................................................................................................................. 50
setStopAction................................................................................................................................................... 50
stop .................................................................................................................................................................. 51
Object....................................................................................................................................................................... 52
getBaseClass................................................................................................................................................... 52
getClass........................................................................................................................................................... 52
isInstanceOf..................................................................................................................................................... 52
Particles ................................................................................................................................................................... 53
new .................................................................................................................................................................. 53
addParticles ..................................................................................................................................................... 53
clearTexture..................................................................................................................................................... 53
getParticleAngle............................................................................................................................................... 53
getParticleColor ............................................................................................................................................... 53
getParticleDecay.............................................................................................................................................. 54
getParticlePosition ........................................................................................................................................... 54
getParticles ...................................................................................................................................................... 54
getParticleSize................................................................................................................................................. 54
getParticleSpeed ............................................................................................................................................. 54
getParticleTag.................................................................................................................................................. 55
getParticleTtl.................................................................................................................................................... 55
isPaused .......................................................................................................................................................... 55
removeParticles ............................................................................................................................................... 55
setParticleAngle............................................................................................................................................... 55
setParticleColor ............................................................................................................................................... 55
setParticleDecay.............................................................................................................................................. 56
setParticlePosition ........................................................................................................................................... 56
setParticleSize ................................................................................................................................................. 56
setParticleSpeed.............................................................................................................................................. 56
setParticlesTag ................................................................................................................................................ 56
setParticleTag.................................................................................................................................................. 56
setParticleTtl .................................................................................................................................................... 57
setPaused........................................................................................................................................................ 57
setTexture........................................................................................................................................................ 57
Path2D ..................................................................................................................................................................... 58
new .................................................................................................................................................................. 58
setConvex........................................................................................................................................................ 58
setFillColor....................................................................................................................................................... 58
setFontPath ..................................................................................................................................................... 58
setLineColor..................................................................................................................................................... 59
setLineThickness ............................................................................................................................................. 59
setPath............................................................................................................................................................. 59
setSvgPath ...................................................................................................................................................... 59
setTexture........................................................................................................................................................ 60
Pixel ......................................................................................................................................................................... 61
new .................................................................................................................................................................. 61
getColor ........................................................................................................................................................... 61
getDimensions ................................................................................................................................................. 62
getTexturePosition........................................................................................................................................... 62
getTextureScale............................................................................................................................................... 62
setColor ........................................................................................................................................................... 62
setDimensions ................................................................................................................................................. 64
setHeight.......................................................................................................................................................... 64
setTexture........................................................................................................................................................ 64
setTextureMatrix .............................................................................................................................................. 64
setTexturePosition ........................................................................................................................................... 64
setTextureScale............................................................................................................................................... 65
setWidth........................................................................................................................................................... 65
RenderTarget........................................................................................................................................................... 66
new .................................................................................................................................................................. 66
clear ................................................................................................................................................................. 66
draw ................................................................................................................................................................. 66
getPixel ............................................................................................................................................................ 67
getPixels .......................................................................................................................................................... 67
save ................................................................................................................................................................. 67
Screen...................................................................................................................................................................... 68
new .................................................................................................................................................................. 68
clear ................................................................................................................................................................. 68
getId................................................................................................................................................................. 68
getMaxSize ...................................................................................................................................................... 68
getPosition ....................................................................................................................................................... 68
getSize............................................................................................................................................................. 68
getState ........................................................................................................................................................... 68
setContent ....................................................................................................................................................... 69
setPosition ....................................................................................................................................................... 69
setSize ............................................................................................................................................................. 69
setState............................................................................................................................................................ 69
Shader ..................................................................................................................................................................... 70
new .................................................................................................................................................................. 70
getEngineVersion ............................................................................................................................................ 71
getShaderLanguage ........................................................................................................................................ 71
setConstant...................................................................................................................................................... 71
Shape....................................................................................................................................................................... 72
new .................................................................................................................................................................. 72
beginPath......................................................................................................................................................... 72
clear ................................................................................................................................................................. 72
closePath ......................................................................................................................................................... 72
endPath ........................................................................................................................................................... 72
lineTo ............................................................................................................................................................... 72
moveTo............................................................................................................................................................ 73
setFillStyle ....................................................................................................................................................... 73
setLineStyle ..................................................................................................................................................... 73
Sound....................................................................................................................................................................... 75
new .................................................................................................................................................................. 75
setListenerPosition .......................................................................................................................................... 75
getLength......................................................................................................................................................... 75
play .................................................................................................................................................................. 75
SoundChannel ......................................................................................................................................................... 77
getPitch............................................................................................................................................................ 77
getPosition ....................................................................................................................................................... 77
getVolume........................................................................................................................................................ 77
isLooping ......................................................................................................................................................... 77
isPaused .......................................................................................................................................................... 77
isPlaying .......................................................................................................................................................... 77
setLooping ....................................................................................................................................................... 77
setPaused........................................................................................................................................................ 78
setPitch ............................................................................................................................................................ 78
setPosition ....................................................................................................................................................... 78
setVolume........................................................................................................................................................ 78
setWorldPosition.............................................................................................................................................. 78
stop .................................................................................................................................................................. 78
Sprite........................................................................................................................................................................ 79
new .................................................................................................................................................................. 79
addChild........................................................................................................................................................... 79
addChildAt ....................................................................................................................................................... 79
clearBlendMode............................................................................................................................................... 79
contains ........................................................................................................................................................... 79
get.................................................................................................................................................................... 79
getAlpha........................................................................................................................................................... 80
getAnchorPosition............................................................................................................................................ 80
getBounds........................................................................................................................................................ 80
getChildAt ........................................................................................................................................................ 81
getChildIndex................................................................................................................................................... 81
getClip.............................................................................................................................................................. 81
getColorTransform........................................................................................................................................... 81
getHeight ......................................................................................................................................................... 81
getMatrix .......................................................................................................................................................... 82
getNumChildren............................................................................................................................................... 82
getParent ......................................................................................................................................................... 82
getPosition ....................................................................................................................................................... 82
getRotation ...................................................................................................................................................... 83
getRotationX .................................................................................................................................................... 83
getRotationY .................................................................................................................................................... 83
getScale........................................................................................................................................................... 83
getScaleX ........................................................................................................................................................ 83
getScaleY ........................................................................................................................................................ 83
getScaleZ......................................................................................................................................................... 83
getSkew ........................................................................................................................................................... 83
getSkewX......................................................................................................................................................... 84
getSkewY......................................................................................................................................................... 84
getWidth........................................................................................................................................................... 84
getX ................................................................................................................................................................. 84
getY ................................................................................................................................................................. 84
getZ.................................................................................................................................................................. 84
globalToLocal .................................................................................................................................................. 84
hitTestPoint...................................................................................................................................................... 85
isVisible............................................................................................................................................................ 85
localToGlobal................................................................................................................................................... 85
removeChild..................................................................................................................................................... 85
removeChildAt ................................................................................................................................................. 85
removeFromParent.......................................................................................................................................... 86
set .................................................................................................................................................................... 86
setAlpha........................................................................................................................................................... 86
setAnchorPosition............................................................................................................................................ 87
setBlendMode.................................................................................................................................................. 87
setClip.............................................................................................................................................................. 87
setColorTransform ........................................................................................................................................... 87
setMatrix .......................................................................................................................................................... 88
setPosition ....................................................................................................................................................... 88
setRotation....................................................................................................................................................... 88
setRotationX .................................................................................................................................................... 88
setRotationY .................................................................................................................................................... 88
setScale ........................................................................................................................................................... 88
setScaleX......................................................................................................................................................... 88
setScaleY......................................................................................................................................................... 88
setScaleZ......................................................................................................................................................... 89
setShader ........................................................................................................................................................ 89
setShaderConstant .......................................................................................................................................... 89
setSkew ........................................................................................................................................................... 89
setSkewX......................................................................................................................................................... 89
setSkewY......................................................................................................................................................... 89
setStencilOperation ......................................................................................................................................... 89
setVisible ......................................................................................................................................................... 90
setX.................................................................................................................................................................. 90
setY.................................................................................................................................................................. 90
setZ.................................................................................................................................................................. 90
swapChildren ................................................................................................................................................... 90
swapChildrenAt................................................................................................................................................ 90
Stage........................................................................................................................................................................ 92
setClearColorBuffer ......................................................................................................................................... 92
TextField .................................................................................................................................................................. 93
new .................................................................................................................................................................. 93
getLayout ......................................................................................................................................................... 93
getLetterSpacing.............................................................................................................................................. 93
getLineHeight................................................................................................................................................... 93
getSample........................................................................................................................................................ 93
getText............................................................................................................................................................. 93
getTextColor .................................................................................................................................................... 94
setFont............................................................................................................................................................. 94
setLayout ......................................................................................................................................................... 94
setLetterSpacing.............................................................................................................................................. 94
setSample........................................................................................................................................................ 94
setText ............................................................................................................................................................. 94
setTextColor .................................................................................................................................................... 94
TextInputDialog........................................................................................................................................................ 96
new .................................................................................................................................................................. 96
getInputType.................................................................................................................................................... 96
getText............................................................................................................................................................. 96
isSecureInput................................................................................................................................................... 96
setInputType .................................................................................................................................................... 96
setSecureInput................................................................................................................................................. 97
setText ............................................................................................................................................................. 97
Texture..................................................................................................................................................................... 98
new .................................................................................................................................................................. 98
TextureBase........................................................................................................................................................... 100
getHeight ....................................................................................................................................................... 100
getWidth......................................................................................................................................................... 100
TexturePack........................................................................................................................................................... 101
new ................................................................................................................................................................ 101
getTextureRegion .......................................................................................................................................... 102
TextureRegion ....................................................................................................................................................... 103
new ................................................................................................................................................................ 103
getRegion ...................................................................................................................................................... 104
setRegion....................................................................................................................................................... 104
TileMap .................................................................................................................................................................. 105
new ................................................................................................................................................................ 105
clearTile ......................................................................................................................................................... 105
getTile ............................................................................................................................................................ 105
setTile ............................................................................................................................................................ 105
shift ................................................................................................................................................................ 106
Timer...................................................................................................................................................................... 107
delayedCall .................................................................................................................................................... 107
new ................................................................................................................................................................ 107
pauseAll ......................................................................................................................................................... 107
resumeAll....................................................................................................................................................... 107
stopAll ............................................................................................................................................................ 107
getCurrentCount ............................................................................................................................................ 107
getDelay......................................................................................................................................................... 107
getRepeatCount............................................................................................................................................. 108
isRunning....................................................................................................................................................... 108
reset............................................................................................................................................................... 108
setDelay......................................................................................................................................................... 108
setRepeatCount............................................................................................................................................. 108
start................................................................................................................................................................ 108
stop ................................................................................................................................................................ 108
TTFont ................................................................................................................................................................... 109
new ................................................................................................................................................................ 109
UrlLoader ............................................................................................................................................................... 110
new ................................................................................................................................................................ 111
close .............................................................................................................................................................. 111
ignoreSslErrors .............................................................................................................................................. 111
load ................................................................................................................................................................ 111
Viewport ................................................................................................................................................................. 113
lookAngles ..................................................................................................................................................... 113
lookAt............................................................................................................................................................. 113
setContent ..................................................................................................................................................... 114
setProjection .................................................................................................................................................. 114
setTransform.................................................................................................................................................. 114
Physics API................................................................................................................................................................... 115
b2 ........................................................................................................................................................................... 116
createDistanceJointDef.................................................................................................................................. 116
createFrictionJointDef.................................................................................................................................... 116
createGearJointDef........................................................................................................................................ 117
createMouseJointDef..................................................................................................................................... 117
createPrismaticJointDef ................................................................................................................................. 118
createPulleyJointDef...................................................................................................................................... 119
createRevoluteJointDef ................................................................................................................................. 120
createRopeJointDef ....................................................................................................................................... 120
createWeldJointDef ....................................................................................................................................... 120
createWheelJointDef ..................................................................................................................................... 121
getScale......................................................................................................................................................... 121
setScale ......................................................................................................................................................... 122
b2.Body.................................................................................................................................................................. 123
applyAngularImpulse ..................................................................................................................................... 123
applyForce ..................................................................................................................................................... 123
applyLinearImpulse........................................................................................................................................ 123
applyTorque................................................................................................................................................... 124
createFixture.................................................................................................................................................. 124
destroyFixture ................................................................................................................................................ 124
getAngle......................................................................................................................................................... 124
getAngularDamping ....................................................................................................................................... 124
getAngularVelocity......................................................................................................................................... 125
getGravityScale ............................................................................................................................................. 125
getInertia........................................................................................................................................................ 125
getLinearDamping ......................................................................................................................................... 125
getLinearVelocity ........................................................................................................................................... 125
getLocalCenter .............................................................................................................................................. 125
getLocalPoint ................................................................................................................................................. 125
getLocalVector............................................................................................................................................... 126
getMass ......................................................................................................................................................... 126
getPosition ..................................................................................................................................................... 126
getWorldCenter.............................................................................................................................................. 126
getWorldPoint ................................................................................................................................................ 126
getWorldVector .............................................................................................................................................. 126
isActive .......................................................................................................................................................... 127
isAwake ......................................................................................................................................................... 127
isBullet ........................................................................................................................................................... 127
isFixedRotation .............................................................................................................................................. 127
isSleepingAllowed.......................................................................................................................................... 127
setActive ........................................................................................................................................................ 127
setAngle......................................................................................................................................................... 128
setAngularDamping ....................................................................................................................................... 128
setAngularVelocity ......................................................................................................................................... 128
setAwake ....................................................................................................................................................... 128
setBullet ......................................................................................................................................................... 128
setFixedRotation............................................................................................................................................ 128
setGravityScale.............................................................................................................................................. 128
setLinearDamping.......................................................................................................................................... 128
setLinearVelocity ........................................................................................................................................... 129
setPosition ..................................................................................................................................................... 129
setSleepingAllowed ....................................................................................................................................... 129
b2.ChainShape ...................................................................................................................................................... 130
new ................................................................................................................................................................ 130
createChain ................................................................................................................................................... 130
createLoop..................................................................................................................................................... 130
b2.CircleShape ...................................................................................................................................................... 131
new ................................................................................................................................................................ 131
set .................................................................................................................................................................. 131
b2.Contact.............................................................................................................................................................. 132
getChildIndexA .............................................................................................................................................. 132
getChildIndexB .............................................................................................................................................. 132
getFixtureA .................................................................................................................................................... 132
getFixtureB .................................................................................................................................................... 132
getFriction ...................................................................................................................................................... 132
getManifold .................................................................................................................................................... 133
getRestitution................................................................................................................................................. 133
getWorldManifold........................................................................................................................................... 133
isTouching ..................................................................................................................................................... 133
resetFriction ................................................................................................................................................... 133
resetRestitution.............................................................................................................................................. 133
setEnabled..................................................................................................................................................... 133
setFriction ...................................................................................................................................................... 133
setRestitution ................................................................................................................................................. 134
b2.DebugDraw ....................................................................................................................................................... 135
new ................................................................................................................................................................ 135
appendFlags .................................................................................................................................................. 135
clearFlags ...................................................................................................................................................... 135
getFlags ......................................................................................................................................................... 135
setFlags ......................................................................................................................................................... 135
b2.DistanceJoint .................................................................................................................................................... 136
getDampingRatio ........................................................................................................................................... 136
getFrequency................................................................................................................................................. 136
getLength....................................................................................................................................................... 136
setDampingRatio ........................................................................................................................................... 136
setFrequency ................................................................................................................................................. 136
setLength ....................................................................................................................................................... 136
b2.EdgeShape ....................................................................................................................................................... 138
new ................................................................................................................................................................ 138
set .................................................................................................................................................................. 138
b2.Fixture ............................................................................................................................................................... 139
getBody.......................................................................................................................................................... 139
getFilterData .................................................................................................................................................. 139
isSensor......................................................................................................................................................... 139
setFilterData .................................................................................................................................................. 140
setSensor....................................................................................................................................................... 140
b2.FrictionJoint....................................................................................................................................................... 142
getMaxForce.................................................................................................................................................. 142
getMaxTorque................................................................................................................................................ 142
setMaxForce .................................................................................................................................................. 142
setMaxTorque................................................................................................................................................ 142
b2.GearJoint .......................................................................................................................................................... 143
getRatio ......................................................................................................................................................... 143
setRatio.......................................................................................................................................................... 143
b2.Joint .................................................................................................................................................................. 144
getAnchorA .................................................................................................................................................... 144
getAnchorB .................................................................................................................................................... 144
getBodyA ....................................................................................................................................................... 144
getBodyB ....................................................................................................................................................... 144
getReactionForce .......................................................................................................................................... 144
getReactionTorque ........................................................................................................................................ 144
getType.......................................................................................................................................................... 145
isActive .......................................................................................................................................................... 145
b2.Manifold ............................................................................................................................................................ 146
b2.MouseJoint........................................................................................................................................................ 147
getDampingRatio ........................................................................................................................................... 147
getFrequency................................................................................................................................................. 147
getMaxForce.................................................................................................................................................. 147
getTarget ....................................................................................................................................................... 147
setDampingRatio ........................................................................................................................................... 148
setFrequency ................................................................................................................................................. 148
setMaxForce .................................................................................................................................................. 148
setTarget........................................................................................................................................................ 148
b2.ParticleSystem .................................................................................................................................................. 149
containsParticle ............................................................................................................................................. 149
createParticle................................................................................................................................................. 149
createParticleGroup....................................................................................................................................... 150
destroyParticle ............................................................................................................................................... 150
destroyParticles ............................................................................................................................................. 150
getParticleCount ............................................................................................................................................ 150
getParticleGroupList ...................................................................................................................................... 150
setTexture...................................................................................................................................................... 150
b2.PolygonShape................................................................................................................................................... 151
new ................................................................................................................................................................ 151
set .................................................................................................................................................................. 151
setAsBox........................................................................................................................................................ 151
b2.PrismaticJoint.................................................................................................................................................... 152
enableLimit .................................................................................................................................................... 152
enableMotor................................................................................................................................................... 152
getJointSpeed................................................................................................................................................ 152
getJointTranslation ........................................................................................................................................ 152
getLimits ........................................................................................................................................................ 152
getMotorSpeed .............................................................................................................................................. 152
isLimitEnabled ............................................................................................................................................... 153
isMotorEnabled.............................................................................................................................................. 153
setLimits......................................................................................................................................................... 153
setMaxMotorForce......................................................................................................................................... 153
setMotorSpeed .............................................................................................................................................. 153
b2.RevoluteJoint:getMotorForce.................................................................................................................... 153
b2.PulleyJoint......................................................................................................................................................... 154
getGroundAnchorA ........................................................................................................................................ 154
getGroundAnchorB ........................................................................................................................................ 154
getLengthA .................................................................................................................................................... 154
getLengthB .................................................................................................................................................... 154
getRatio ......................................................................................................................................................... 154
b2.RevoluteJoint .................................................................................................................................................... 155
enableLimit .................................................................................................................................................... 155
enableMotor................................................................................................................................................... 155
getJointAngle ................................................................................................................................................. 155
getJointSpeed................................................................................................................................................ 155
getLimits ........................................................................................................................................................ 155
getMotorSpeed .............................................................................................................................................. 155
getMotorTorque ............................................................................................................................................. 156
isLimitEnabled ............................................................................................................................................... 156
isMotorEnabled.............................................................................................................................................. 156
setLimits......................................................................................................................................................... 156
setMaxMotorTorque....................................................................................................................................... 156
setMotorSpeed .............................................................................................................................................. 156
b2.RopeJoint.......................................................................................................................................................... 157
getMaxLength ................................................................................................................................................ 157
setMaxLength ................................................................................................................................................ 157
b2.Shape................................................................................................................................................................ 158
b2.WeldJoint .......................................................................................................................................................... 159
getDampingRatio ........................................................................................................................................... 159
getFrequency................................................................................................................................................. 159
setDampingRatio ........................................................................................................................................... 159
setFrequency ................................................................................................................................................. 159
b2.WheelJoint ........................................................................................................................................................ 160
enableMotor................................................................................................................................................... 160
getJointSpeed................................................................................................................................................ 160
getJointTranslation ........................................................................................................................................ 160
getMaxMotorTorque ...................................................................................................................................... 160
getMotorSpeed .............................................................................................................................................. 160
getSpringDampingRatio................................................................................................................................. 160
getSpringFrequencyHz .................................................................................................................................. 161
isMotorEnabled.............................................................................................................................................. 161
setMaxMotorTorque....................................................................................................................................... 161
setMotorSpeed .............................................................................................................................................. 161
setSpringDampingRatio................................................................................................................................. 161
setSpringFrequencyHz .................................................................................................................................. 161
b2.World................................................................................................................................................................. 162
new ................................................................................................................................................................ 163
clearForces .................................................................................................................................................... 163
createBody..................................................................................................................................................... 163
createJoint ..................................................................................................................................................... 164
createParticleSystem..................................................................................................................................... 166
destroyBody................................................................................................................................................... 167
destroyJoint ................................................................................................................................................... 167
getGravity ...................................................................................................................................................... 167
queryAABB .................................................................................................................................................... 167
rayCast .......................................................................................................................................................... 168
setDebugDraw ............................................................................................................................................... 168
setGravity....................................................................................................................................................... 168
step ................................................................................................................................................................ 169
b2.WorldManifold ................................................................................................................................................... 170
Lua API.......................................................................................................................................................................... 171
(global) ................................................................................................................................................................... 172
assert ............................................................................................................................................................. 172
collectgarbage ............................................................................................................................................... 172
dofile .............................................................................................................................................................. 172
error ............................................................................................................................................................... 172
getfenv ........................................................................................................................................................... 172
getmetatable .................................................................................................................................................. 173
ipairs .............................................................................................................................................................. 173
loadfile ........................................................................................................................................................... 173
loadstring ....................................................................................................................................................... 173
next ................................................................................................................................................................ 174
pairs ............................................................................................................................................................... 174
pcall ............................................................................................................................................................... 174
print................................................................................................................................................................ 174
rawequal ........................................................................................................................................................ 175
rawget ............................................................................................................................................................ 175
rawset ............................................................................................................................................................ 175
require............................................................................................................................................................ 175
setfenv ........................................................................................................................................................... 175
setmetatable .................................................................................................................................................. 176
tonumber........................................................................................................................................................ 176
tostring ........................................................................................................................................................... 176
type ................................................................................................................................................................ 177
unpack ........................................................................................................................................................... 177
xpcall.............................................................................................................................................................. 177
coroutine ................................................................................................................................................................ 178
create............................................................................................................................................................. 178
resume........................................................................................................................................................... 179
status ............................................................................................................................................................. 179
wrap ............................................................................................................................................................... 179
yield ............................................................................................................................................................... 179
debug ..................................................................................................................................................................... 181
debug............................................................................................................................................................. 181
gethook .......................................................................................................................................................... 181
getinfo ............................................................................................................................................................ 181
getlocal .......................................................................................................................................................... 181
getupvalue ..................................................................................................................................................... 182
sethook .......................................................................................................................................................... 182
setlocal........................................................................................................................................................... 182
settypemt ....................................................................................................................................................... 183
setupvalue ..................................................................................................................................................... 183
traceback ....................................................................................................................................................... 183
file .......................................................................................................................................................................... 184
close .............................................................................................................................................................. 184
flush ............................................................................................................................................................... 184
lines ............................................................................................................................................................... 184
read................................................................................................................................................................ 184
seek ............................................................................................................................................................... 185
write ............................................................................................................................................................... 185
int64 ....................................................................................................................................................................... 186
new ................................................................................................................................................................ 186
io ............................................................................................................................................................................ 187
close .............................................................................................................................................................. 187
flush ............................................................................................................................................................... 187
input ............................................................................................................................................................... 187
lines ............................................................................................................................................................... 187
open............................................................................................................................................................... 188
output............................................................................................................................................................. 188
read................................................................................................................................................................ 188
tmpfile ............................................................................................................................................................ 188
type ................................................................................................................................................................ 188
write ............................................................................................................................................................... 189
math ....................................................................................................................................................................... 190
abs ................................................................................................................................................................. 190
acos ............................................................................................................................................................... 190
asin ................................................................................................................................................................ 190
atan................................................................................................................................................................ 190
atan2.............................................................................................................................................................. 190
ceil ................................................................................................................................................................. 191
cos ................................................................................................................................................................. 191
deg................................................................................................................................................................. 191
exp ................................................................................................................................................................. 191
floor................................................................................................................................................................ 191
fmod............................................................................................................................................................... 192
frexp............................................................................................................................................................... 192
ldexp .............................................................................................................................................................. 192
log .................................................................................................................................................................. 192
log10 .............................................................................................................................................................. 192
max ................................................................................................................................................................ 193
min ................................................................................................................................................................. 193
pow ................................................................................................................................................................ 193
rad.................................................................................................................................................................. 193
random........................................................................................................................................................... 193
randomseed................................................................................................................................................... 194
sin .................................................................................................................................................................. 194
sqrt................................................................................................................................................................. 194
tan.................................................................................................................................................................. 194
os ........................................................................................................................................................................... 195
clock............................................................................................................................................................... 195
date................................................................................................................................................................ 195
difftime ........................................................................................................................................................... 195
execute .......................................................................................................................................................... 195
exit ................................................................................................................................................................. 195
getenv ............................................................................................................................................................ 196
remove........................................................................................................................................................... 196
rename........................................................................................................................................................... 196
setlocale......................................................................................................................................................... 196
time ................................................................................................................................................................ 196
timer............................................................................................................................................................... 197
tmpname........................................................................................................................................................ 197
package ................................................................................................................................................................. 198
loadlib ............................................................................................................................................................ 198
string ...................................................................................................................................................................... 199
byte ................................................................................................................................................................ 199
char................................................................................................................................................................ 199
dump.............................................................................................................................................................. 199
find ................................................................................................................................................................. 199
format............................................................................................................................................................. 200
gmatch ........................................................................................................................................................... 200
gsub ............................................................................................................................................................... 200
len .................................................................................................................................................................. 201
lower .............................................................................................................................................................. 201
match ............................................................................................................................................................. 201
rep.................................................................................................................................................................. 202
sub ................................................................................................................................................................. 202
upper.............................................................................................................................................................. 202
table ....................................................................................................................................................................... 203
concat ............................................................................................................................................................ 203
getn................................................................................................................................................................ 203
insert .............................................................................................................................................................. 203
remove........................................................................................................................................................... 203
sort................................................................................................................................................................. 203
utf8 ......................................................................................................................................................................... 205
byte ................................................................................................................................................................ 205
char................................................................................................................................................................ 205
charpos .......................................................................................................................................................... 205
codepoint ....................................................................................................................................................... 205
codes ............................................................................................................................................................. 206
escape ........................................................................................................................................................... 206
find ................................................................................................................................................................. 206
fold ................................................................................................................................................................. 206
gmatch ........................................................................................................................................................... 207
gsub ............................................................................................................................................................... 207
insert .............................................................................................................................................................. 207
len .................................................................................................................................................................. 208
lower .............................................................................................................................................................. 208
match ............................................................................................................................................................. 208
ncasecmp ...................................................................................................................................................... 208
next ................................................................................................................................................................ 209
offset .............................................................................................................................................................. 209
remove........................................................................................................................................................... 209
reverse........................................................................................................................................................... 209
sub ................................................................................................................................................................. 210
title ................................................................................................................................................................. 210
upper.............................................................................................................................................................. 210
width .............................................................................................................................................................. 210
widthindex...................................................................................................................................................... 211
zlib.......................................................................................................................................................................... 212
adler32........................................................................................................................................................... 212
compress ....................................................................................................................................................... 212
crc32 .............................................................................................................................................................. 212
decompress ................................................................................................................................................... 212
deflate ............................................................................................................................................................ 213
inflate ............................................................................................................................................................. 213
Plugins .......................................................................................................................................................................... 214
Ads......................................................................................................................................................................... 215
new ................................................................................................................................................................ 215
enableTesting ................................................................................................................................................ 215
get.................................................................................................................................................................. 215
getHeight ....................................................................................................................................................... 216
getPosition ..................................................................................................................................................... 216
getWidth......................................................................................................................................................... 216
getX ............................................................................................................................................................... 216
getY ............................................................................................................................................................... 216
hideAd............................................................................................................................................................ 216
set .................................................................................................................................................................. 216
setAlignment .................................................................................................................................................. 217
setKey............................................................................................................................................................ 217
setPosition ..................................................................................................................................................... 217
setX................................................................................................................................................................ 217
setY................................................................................................................................................................ 217
showAd .......................................................................................................................................................... 217
bit ........................................................................................................................................................................... 218
arshift ............................................................................................................................................................. 218
band............................................................................................................................................................... 218
bnot................................................................................................................................................................ 218
bor.................................................................................................................................................................. 218
bswap ............................................................................................................................................................ 218
bxor................................................................................................................................................................ 219
lshift ............................................................................................................................................................... 219
rol................................................................................................................................................................... 219
ror .................................................................................................................................................................. 219
rshift ............................................................................................................................................................... 220
tobit ................................................................................................................................................................ 220
tohex .............................................................................................................................................................. 220
bump ...................................................................................................................................................................... 221
camera ................................................................................................................................................................... 222
availableDevices............................................................................................................................................ 222
start................................................................................................................................................................ 222
stop ................................................................................................................................................................ 222
Controller ............................................................................................................................................................... 223
getControllerName......................................................................................................................................... 223
getPlayerCount .............................................................................................................................................. 224
getPlayers...................................................................................................................................................... 224
isAnyAvailable ............................................................................................................................................... 224
vibrate ............................................................................................................................................................ 224
Facebook ............................................................................................................................................................... 225
authorize ........................................................................................................................................................ 225
dialog ............................................................................................................................................................. 225
extendAccessToken ...................................................................................................................................... 225
extendAccessTokenIfNeeded........................................................................................................................ 225
getAccessToken ............................................................................................................................................ 225
getExpirationDate .......................................................................................................................................... 225
graphRequest ................................................................................................................................................ 225
isSessionValid ............................................................................................................................................... 226
logout ............................................................................................................................................................. 226
setAccessToken ............................................................................................................................................ 226
setAppId......................................................................................................................................................... 226
setExpirationDate .......................................................................................................................................... 226
shouldExtendAccessToken ........................................................................................................................... 226
flurry ....................................................................................................................................................................... 227
endTimedEvent.............................................................................................................................................. 227
isAvailable...................................................................................................................................................... 227
logEvent......................................................................................................................................................... 227
startSession ................................................................................................................................................... 227
GoogleBilling.......................................................................................................................................................... 228
checkBillingSupported ................................................................................................................................... 228
confirmNotification ......................................................................................................................................... 228
requestPurchase............................................................................................................................................ 229
restoreTransactions ....................................................................................................................................... 229
setApiVersion................................................................................................................................................. 229
setPublicKey .................................................................................................................................................. 229
iad .......................................................................................................................................................................... 230
isAvailable...................................................................................................................................................... 230
iad.Banner.............................................................................................................................................................. 231
new ................................................................................................................................................................ 231
hide ................................................................................................................................................................ 232
isBannerLoaded............................................................................................................................................. 232
setAlignment .................................................................................................................................................. 232
show .............................................................................................................................................................. 232
json ........................................................................................................................................................................ 234
decode ........................................................................................................................................................... 234
encode ........................................................................................................................................................... 234
lfs ........................................................................................................................................................................... 235
lpeg ........................................................................................................................................................................ 236
Microphone ............................................................................................................................................................ 237
new ................................................................................................................................................................ 237
setOutputFile ................................................................................................................................................. 237
start................................................................................................................................................................ 237
stop ................................................................................................................................................................ 237
Notification ............................................................................................................................................................. 238
new ................................................................................................................................................................ 238
cancel ............................................................................................................................................................ 239
dispatchAfter.................................................................................................................................................. 239
dispatchNow .................................................................................................................................................. 239
dispatchOn..................................................................................................................................................... 239
getId............................................................................................................................................................... 239
getMessage ................................................................................................................................................... 239
getNumber ..................................................................................................................................................... 239
getSound ....................................................................................................................................................... 240
getTitle ........................................................................................................................................................... 240
setNumber ..................................................................................................................................................... 240
setSound........................................................................................................................................................ 240
setTitle ........................................................................................................................................................... 240
NotificationManager ............................................................................................................................................... 241
getSharedInstance......................................................................................................................................... 242
cancelAllNotifications..................................................................................................................................... 242
cancelNotification........................................................................................................................................... 242
clearLocalNotifications................................................................................................................................... 243
clearPushNotifications ................................................................................................................................... 243
getLocalNotifications...................................................................................................................................... 243
getPushNotifications ...................................................................................................................................... 243
getScheduledNotifications ............................................................................................................................. 244
registerForPushNotifications.......................................................................................................................... 244
unregisterForPushNotifications...................................................................................................................... 245
sqlite3..................................................................................................................................................................... 246
StoreKit .................................................................................................................................................................. 247
canMakePayments ........................................................................................................................................ 248
finishTransaction............................................................................................................................................ 248
purchase ........................................................................................................................................................ 248
requestProducts............................................................................................................................................. 248
restoreCompletedTransactions...................................................................................................................... 248
Lua Enhancements
This is a decription of what the Lua enhancements are.

Better and easier syntax for arrays 2017.11+


Operators to return the larger or smaller of two values.a=b[c<b> , </b>d] The same as 'a=b[c][d]' but
shorter and easier to understand and read.

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

Binary Numbers 2017.10+


Binary number representation.<b>0b</b>BinaryPattern Enter a number in binary format.

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

Bitwise Operators 2017.10+


Bitwise operators to manipulate numbers.a<b> | </b>b Bitwise 'a OR b'.a<b> & </b>b Bitwise 'a AND
b'.a<b> ~ </b>b Bitwise 'a XOR b'.a<b> << </b>b Bitwise shift 'a' by 'b' left.a<b> >> </b>b Bitwise
shift 'a' by 'b' right.<b> ~ </b>a Bitwise 'NOT a'.

Set joypad switches

if k==KeyCode.UP then joypad=joypad|0b001000


elseif k==KeyCode.DOWN then joypad=joypad|0b000100
elseif k==KeyCode.LEFT then joypad=joypad|0b000010
elseif k==KeyCode.RIGHT then joypad=joypad|0b000001
end

Clear joypad switches

if k==KeyCode.UP then joypad=joypad&0b0111


elseif k==KeyCode.DOWN then joypad=joypadRGUDLR&0b1011
elseif k==KeyCode.LEFT then joypad=joypadRGUDLR&0b1101
elseif k==KeyCode.RIGHT then joypad=joypadRGUDLR&0b1110
end

Gideros API Reference v2017.12 Page 1


Move in a direction based on joystick switches (using above examples)

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]

Debounce bits, eg joypad switches

joypad=(joypad~joypadOld)&joypad
joypadOld=joypad

Integer Divide Operator 2017.10+


Divide a number to a whole number.a=b<b> // </b>c Put the integer result of divide 'b' by 'c' into 'a'.

Simple example

a=b//c -- faster than a=math.floor(b/c)

Larger and Smaller Operators 2017.10+


Operators to return the larger or smaller of two values.a<b> <> </b>b Compare 'a' and 'b', return the larger
of them.a<b> >< </b>b Compare 'a' and 'b', return the smaller of them.

Simple larger examples

x=a<>b -- faster than x=math.max(a,b)


x=(x-1)<>5 -- decrement x, but don't go below 5

Simple smaller examples

x=a><b -- faster than x=math.min(a,b)


x=(x+1)><15 -- increment x, but don't go above 15

Make sure x is within bounds example

x=(x<>min)><max

Always return the negative of a number

x=-x><x -- faster than -math.abs

Always return the positive of a number

x=-x<>x -- faster than math.abs

Macro Constants 2017.10+


Macro Constants can be used for string and numeric constants.Just use @ rather than = when defining the
macro.You can use any of these delimiters after @ but they must be used in pairs. Numbers are
auto-detected.\`~ ! # $ % ^ & * / + = |

Gideros API Reference v2017.12 Page 2


Simple examples

pi@3.14159265358979324
num1 @ -100.54
num2 @ 232
num3 @ 444.10
str1 @ 'hello'
str2 @ "world"
str3 @ [[
Hello,
world!
]]

Commenting out the print command

print @ |--|

print(x, y, z, x+y, y*z) -- this line will be skipped

Macro Functions 2017.10+


Macro Functions receive a list of tokens and output a string which will be pasted into code at compile
time.name @ (| ...body... |)You should use parenthesis around markers - '|' is the preferred marker. The
same marker should be used to close macro body with closing parenthesis right after it.You can use any of
these markers.\`~ ! # $ % ^ & * / + = |You can redefine a macro with @@.name @@ (| ...another_body...
|)To call macro function use it's name with parenthesis as with usual functions:name(...arguments...)

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, " ")
|)

enum(apple, orange, melon)


print(apple, orange, melon) --> 1 2 3

Turning off the print command

print @ (| return "" |)

Unroll loops

dotimes @ (|
local times=table.remove(..., 1)
return (table.concat(..., " ").." "):rep(times)
|)

Gideros API Reference v2017.12 Page 3


local t={}

dotimes(10 print "Boom!")

Mutation Operators 2017.11+


Operators to mutate a value.a<b> += </b>b Add 'b' to 'a'.a<b> -= </b>b Subtract 'b from 'a'.a<b> *=
</b>b Multiply 'a' by 'b', result in 'a'.a<b> /= </b>b Divide 'a' by 'b', result in 'a'.a<b> %= </b>b The
result of 'a%b' is placed in 'a'.a<b> ^= </b>b The result of 'a^b' is placed in 'a'. ^ is faster than
a=math.pow(a,b)

Simple larger example

score+=1 -- faster and less typing than score=score+1

Octal Numbers 2017.10+


Octal number representation.<b>0o</b>OctalPattern Enter a number in octal format.

Simple examples

a=0o10 -- a=8
a=0o112 -- a=74

Trigonometry Conversion Operators 2017.10+


Operators to convert from one type of measurement to another.<b> ^< </b>deg Convert 'deg' into
radians.<b> ^> </b>rad Convert 'rad' into degrees.

Simple ^< examples

r=^<d -- faster than r=math.rad(d)


radAngle=^<sprite:getRotation()
pi=^<180 -- pi is 3.142 in radians or 180 in degrees

Simple ^> examples

d=^>r -- faster than d=math.deg(r)


sprite:setRotation(^>math.sin(0.5))

Universal Bytecode 2017.10+


Unlike other versions of Lua, the exported bytecode with Gideros Lua is automatically compatible with both
32 and 64 bit systems.

Gideros API Reference v2017.12 Page 4


Main API
This is a decription of the Main API.

Gideros API Reference v2017.12 Page 5


Accelerometer Inherits: Object 2012.8+
The `Accelerometer` class is used to access accelerometer data.

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)

--once you don't need it, stop it


accelerometer:stop()

Accelerometer . isAvailable 2012.8+


Returns `true` if accelerometer is available for this platform, `false` otherwise.
bool = Accelerometer.isAvailable()
bool : `true` if accelerometer is available for this platform, `false` otherwise.

Accelerometer . new 2012.8+


Creates new Accelerometer instance
Accelerometer.new()

Accelerometer : getAcceleration 2012.8+


Returns the 3-axis acceleration measured by the accelerometer.
num, num, num = Accelerometer:getAcceleration()
num : acceleration on x-axis in G's
num : acceleration on y-axis in G's
num : acceleration on z-axis in G's

Accelerometer : start 2012.8+


Starts the generation of accelerometer samples.
Accelerometer:start()

Accelerometer : stop 2012.8+


Stops the generation of accelerometer samples.
Accelerometer:stop()

Gideros API Reference v2017.12 Page 6


AlertDialog Inherits: Object 2012.8+
The `AlertDialog` class is used to display native alert dialogs with one, two or three buttons. Cancel buttonis
mandatory but other two buttons are optional. When the user presses any button in the alert dialog,it's
dismissed and `Event.COMPLETE` event is dispatched.If alert dialog is dismissed by any other means (by
pressing back button on Android or by pressing close button on desktop), it behaves as cancel button is
pressed.

Example:
local alertDialog=AlertDialog.new('This is my title', 'And my message', 'Cancel', 'Yes', 'No')

local function onComplete(event)


print(event.buttonIndex, event.buttonText)
end

alertDialog:addEventListener(Event.COMPLETE, onComplete)
alertDialog:show()

AlertDialog . new 2012.8+


Creates a new `AlertDialog` object.
AlertDialog.new(title, message, cancelButton [, button1] [, button2])
title : (str) The string that appears in the receiver's title bar. Can be empty string.
message : (str) Descriptive text that provides more details than the title. Can be empty string.
cancelButton : (str) The text of the cancel button.
button1 : (str) The text of the 1st optional button.
button2 : (str) The text of the 2st optional button.

AlertDialog : hide 2012.8+


Hides the alert dialog.
AlertDialog:hide()

AlertDialog : show 2012.8+


Shows the alert dialog.
AlertDialog:show()

Gideros API Reference v2017.12 Page 7


Application Inherits: Object 2011.6+
`Application` class contains the common functions that's available to the current application. There is a global
variable `application` of type `Application` to access these functions.

Application : canOpenUrl 2013.06+


Tests if it is possible to open provided url using `Application:openUrl` method
Application:canOpenUrl(url)
url : (str) url to test if can be opened

Application : configureFrustum 2015.04.04+


Configure the field of view (fov) and far clipping plane for 3D projection.Setting a fov of 0 selects default
orthographic projection (no perspective).The field of view specifies the angle of vision by which the largest
side of the scene is seen. It is used to compute the distance of the eye relative to the screen along the Z
axis:Z=(largest screen dimension/2)/tan(fov/2)is eye location. The far clipping plane specifies the maximum
distance of an object. Objects more distant than the far clipping plane are not drawn.Note the perspective is
oriented so that the full screen is at Z=0 (so sprite:setPosition(x,y,0) will place the sprite at exactly (x,y) pixels
on the screen, irrespective of fov) and distant objects are placed at negative Z values.If the fov is set at
non-zero then perspective projection is activated. If farplane is then not set it takes the default value
100*(screen height). Normally the user should set this value. Note that there is no nearplane in perspective
mode (objects are clipped only at the eye position)If fov is set at 0 then the eye is at +infinity and a near
plane is set at z=+farplane. Objects closer than this are clipped. The farplane remains at z=-farplane.
Application:configureFrustum(fov [, farplane])
fov : (num) Specifies the field of view angle in degrees If fov>0 a perspective projection is used with the eye
at position z=+h/tan(fov/2) where h is half the larger screen dimension (logical coordinates). In this case there
is a farplane but no nearplane: clipping is done only at the eye position. If fov=0, an orthographic projection is
used with both a farplane and a nearplane (see below)
farplane : (num) The distance of the far clipping plane along Z axis. If fov>0 and this value is not set, the
farplane is set at distance 100*(screen height) from the origin (z=0). If fov=0 (orthographic projection), a
nearplane is also used at distance farplane from the origin. If fov=0 and no farplane is set then near and
farplanes are set at 1 pixel from the origin.

Application : exit 2012.2.2+


Terminates the application. Although this function is available to all platforms, it should be used on Android
only.
Application:exit()

Application : getApiVersion 2012.08.2+


Returns the API version.
str = Application:getApiVersion()
str : The API version.

Application : getAppId 2017.11.2+


returns the application identifier or bundle identifier.
str = Application:getAppId()

Gideros API Reference v2017.12 Page 8


str : App id

Application : getBackgroundColor 2011.6+


Returns the background color (or clear color) of the application in hexadecimal format.
color = Application:getBackgroundColor()
color : The background color in hexadecimal format.

Application : getContentHeight 2011.6+


If the orientation is portrait, this function returns logical height. If the orientation is landscape, this
functionreturns logical width.
num = Application:getContentHeight()
num : Logical width or logical height depending on orientation.

Application : getContentWidth 2011.6+


If the orientation is portrait, this function returns logical width. If the orientation is landscape, this
functionreturns logical height.
num = Application:getContentWidth()
num : Logical width or logical height depending on orientation.

Application : getDeviceHeight 2011.6+


Returns the physical height of the device in pixels. For example,for iPhone 3GS this function returns 480 and
for iPhone 4 (with retina display enabled) this function returns 960.
num = Application:getDeviceHeight()
num : The physical height of the device in pixels

Application : getDeviceInfo 2011.6+


Returns information about device.- For iOS, returns 5 values: 'iOS', iOS version, device type, user interface
idiom and device model- For Android, returns 4 values: 'Android', Android version, manufacturer and model
information- For Windows returns 1 value: 'Windows'- For Mac OS X returns 1 value: 'Mac OS'- For Win32
returns 1 value: 'Win32'`iOS values`1st value -> "iOS"2nd value -> [[UIDevice currentDevice]
systemVersion]3rd value -> [[UIDevice currentDevice] model]4th value -> UI_USER_INTERFACE_IDIOM()
(as "iPhone" or "iPad")5th value -> hw.machine. Here are the possibilities:iPhone1,1 -> iPhone 1G,
M68iPhone1,2 -> iPhone 3G, N82iPhone2,1 -> iPhone 3GS, N88iPhone3,1 -> iPhone 4/AT&T, N89iPhone3,2
-> iPhone 4/Other Carrier?, ??iPhone3,3 -> iPhone 4/Verizon, TBDiPhone4,1 -> (iPhone 4S/GSM),
TBDiPhone4,2 -> (iPhone 4S/CDMA), TBDiPhone4,3 -> (iPhone 4S/???)iPhone5,1 -> iPhone Next Gen,
TBDiPhone5,1 -> iPhone Next Gen, TBDiPhone5,1 -> iPhone Next Gen, TBD iPod1,1 -> iPod touch 1G,
N45iPod2,1 -> iPod touch 2G, N72iPod2,2 -> Unknown, ??iPod3,1 -> iPod touch 3G, N18iPod4,1 -> iPod
touch 4G, N80 iPad1,1 -> iPad 1G, WiFi and 3G, K48iPad2,1 -> iPad 2G, WiFi, K93iPad2,2 -> iPad 2G, GSM
3G, K94iPad2,3 -> iPad 2G, CDMA 3G, K95iPad3,1 -> (iPad 3G, WiFi)iPad3,2 -> (iPad 3G, GSM)iPad3,3 ->
(iPad 3G, CDMA)iPad4,1 -> (iPad 4G, WiFi)iPad4,2 -> (iPad 4G, GSM)iPad4,3 -> (iPad 4G, CDMA) i386,
x86_64 -> iPhone Simulator`Android values`1st value -> "Android"2nd value ->
android.os.Build.VERSION.SDK_INT3rd value -> android.os.Build.MANUFACTURER4th value ->
android.os.Build.MODEL
varies = Application:getDeviceInfo()
varies : Information about device, returned informations varies depending on platform

Gideros API Reference v2017.12 Page 9


Application : getDeviceOrientation 2014.01+
Get the device orientation (and not what is that in project properties as done with `getOrientation`).Check
Accelerometer example project for usage
str = Application:getDeviceOrientation()
str : Values "portrait", "portraitUpsideDown", "landscapeLeft", "landscapeRight"

Application : getDeviceSafeArea 2017.11.3+


Some screens have non rectangular shapes, in which case it is useful to know the bounds of the safe area,
that is area that is guaranteed to be visible and user accessible. This functions returns the minimum and
maximum coordinates to use, either in physical coordinates or in logical coordinates.
num, num, num, num = Application:getDeviceSafeArea([logical])

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

Application : getDeviceWidth 2011.6+


Returns the physical width of the device in pixels. For example,for iPhone 3GS this function returns 320 and
for iPhone 4 (with retina display enabled) this function returns 640.
num = Application:getDeviceWidth()
num : The physical width of the device in pixels

Application : getFps 2012.2.2+


Returns the frame rate of the application.
num = Application:getFps()
num : The frame rate of the application.

Application : getLanguage 2011.6+


Returns the user language in ISO 639-1 format.
str = Application:getLanguage()
str : The the user language

Application : getLocale 2011.6+


Returns the device locale. The locale string is a combination of ISO 639-1 and ISO 3166-1. For example,
en_US, ja_JP.
str = Application:getLocale()
str : The device locale

Application : getLogicalBounds 2017.11.3+

Gideros API Reference v2017.12 Page 10


Returns the minimum and maximum logical space coordinates to cover full screen.
num, num, num, num = Application:getLogicalBounds()
num : Minimum x
num : Minimum y
num : Maximum x
num : Maximum y

Application : getLogicalHeight 2011.6+


Returns the logical height of the application that is specified at the project properties.
num = Application:getLogicalHeight()
num : The logical height of the application

Application : getLogicalScaleX 2011.6+


Returns the scaling of automatic screen scaling on the x-axis.
num = Application:getLogicalScaleX()
num : The scaling of automatic screen scaling on the x-axis.

Application : getLogicalScaleY 2011.6+


Returns the scaling of automatic screen scaling on the y-axis.
num = Application:getLogicalScaleY()
num : The scaling of automatic screen scaling on the y-axis.

Application : getLogicalTranslateX 2011.6+


Returns the translation of automatic screen scaling on the x-axis.
num = Application:getLogicalTranslateX()
num : The translation of automatic screen scaling on the x-axis.

Application : getLogicalTranslateY 2011.6+


Returns the translation of automatic screen scaling on the y-axis.
num = Application:getLogicalTranslateY()
num : The translation of automatic screen scaling on the y-axis.

Application : getLogicalWidth 2011.6+


Returns the logical width of the application that is specified at the project properties.
num = Application:getLogicalWidth()
num : The logical width of the application

Application : getOrientation 2011.6+


Returns the orientation of the application.
str = Application:getOrientation()
str : Values "portrait", "portraitUpsideDown", "landscapeLeft", "landscapeRight"

Gideros API Reference v2017.12 Page 11


Application : getScaleMode 2012.2.2+
Returns the automatic scale mode of the application.
str = Application:getScaleMode()
str : The automatic scale mode of the application

Application : getScreenDensity 2012.09.2+


Returns the screen density in pixels per inch. If screen density information is not available, returns `nil`.
num = Application:getScreenDensity()
num : If available returns the screen density in pixels per inch, otherwise returns `nil`.

Application : getTextureMemoryUsage 2012.08.3+


Returns the texture memory usage (in Kbytes).
num = Application:getTextureMemoryUsage()
num : The texture memory usage (in Kbytes).

Application : isPlayerMode 2015.03.22+


Returns true if app is ran on Gideros player and false, if it is ran as stand alone app
Application:isPlayerMode()

Application : openUrl 2011.6+


Opens the given URL (Universal Resource Locator) in the appropriate application. URL can be one of the
`http:`, `https:`, `tel:`, or `mailto:` schemes.The following example opens a web page in the
browser:<pre><code>application:openUrl("http://www.giderosmobile.com")</code></pre>If `mailto:`
scheme is specified, the user's e-mail client will be used to open a composer window containing the options
specified in the URL.For example, the following URL contains a recipient (user@foo.com), a subject (Test),
and a message body (Just a
test):<pre><code>application:openUrl('mailto:user@foo.com?subject=Test&amp;body=Just a
test')</code></pre>Or to call a
number:<pre><code>application:openUrl('tel:555-123-4567')</code></pre>
Application:openUrl(url)
url : (str) url to open

Application : setBackgroundColor 2011.6+


Sets the background color (or clear color) of the application in hexadecimal format. Default background color
is white (0xffffff).
Application:setBackgroundColor(color)
color : (num) background color in hexadecimal format

Application : setFps 2012.2.2+


Sets the frame rate of the application. Accepted values are `30` and `60`.You can also use setFps(-60) or
setFps(-30) to maintain an apparent frame rate of 60 or 30 fps by skipping frames if the system notices it is
running slow. So for example, it updates the game logic 60 times per second but redraws the screen 30

Gideros API Reference v2017.12 Page 12


times. The game is playable but will not be so smooth on slow devices. (currently available on WinRT)
Application:setFps(fps)
fps : (num) the new frame rate of the application

Application : setFullScreen 2015.04.12+


Enables full screen mode or windowed mode for desktop app
Application:setFullScreen(fullscreen)
fullscreen : (bool) true for fullscreen, false for windowed mode

Application : setKeepAwake 2011.6+


Controls the screen dimming and device sleeping of the device. When the application has no touches as user
input for some period,the system puts the device into a sleep state where the screen dims. However some
applications have no input and controlledby accelerometer or gyroscope only. For these kind applications,
the screen should be kept awake by calling this functionwith parameter `true`.<ul><li>*Note:** This function
has no effect on desktop.</li></ul>
Application:setKeepAwake(keepAwake)
keepAwake : (bool) if true, screen is kept awake.

Example:
application:setKeepAwake(true) -- disable screen dimming and device sleeping
application:setKeepAwake(false) -- enable screen dimming and device sleeping

Application : setKeyboardVisibility BETA


Show or hide to native on-screen keyboard if available
bool = Application:setKeyboardVisibility(visible)

Parameter:
visible : (bool) if the keyboard should be shown

Result:
bool : true if the device support a native on screen keyboard

Application : setLogicalDimensions 2012.2.2+


Sets the logical dimensions of the application.
Application:setLogicalDimensions(width, height)
width : (num) logical width
height : (num) logical height

Application : setOrientation 2011.6+


Sets the orientation of the application. Accepted values are:<ul><li>Application.PORTRAIT =
'portrait'</li><li>Application.PORTRAIT_UPSIDE_DOWN =
'portraitUpsideDown'</li><li>Application.LANDSCAPE_LEFT =
'landscapeLeft'</li><li>Application.LANDSCAPE_RIGHT = 'landscapeRight'</li></ul>
Application:setOrientation(orientation)
orientation : (str)

Gideros API Reference v2017.12 Page 13


Example:
application:setOrientation(Application.PORTRAIT) -- the buttons are on the bottom
application:setOrientation(Application.PORTRAIT_UPSIDE_DOWN) -- the buttons are at the top
application:setOrientation(Application.LANDSCAPE_LEFT) -- the buttons are on the right side
application:setOrientation(Application.LANDSCAPE_RIGHT) -- the buttons are on the left side

Application : setScaleMode 2012.2.2+


Sets the automatic scale mode of the application. Accepted values are:<ul><li>Application.NO_SCALE =
'noScale'</li><li>Application.CENTER = 'center'</li><li>Application.PIXEL_PERFECT =
'pixelPerfect'</li><li>Application.LETTERBOX = 'letterbox'</li><li>Application.CROP =
'crop'</li><li>Application.STRETCH = 'stretch'</li><li>Application.FIT_WIDTH =
'fitWidth'</li><li>Application.FIT_HEIGHT = 'fitHeight'</li></ul>
Application:setScaleMode(scaleMode)
scaleMode : (str)

Application : setWindowSize 2015.04.12+


Sets desktop window to a specific size
Application:setWindowSize(width, height)
width : (num) new width of the window
height : (num) new height of the window

Application : vibrate 2011.6+


Vibrates the device. If the device doesn't support vibration, this function has no effect.
Application:vibrate([ms])
ms : (num) time in ms for vibration, if supported by the platform. (Android)

Gideros API Reference v2017.12 Page 14


Bitmap Inherits: Sprite 2011.6+
The `Bitmap` class is used to display texture related objects in the scene tree. It is possible to create Bitmap
object from `TextureBase` or `TextureRegion` instances.

Bitmap . new 2011.6+


Creates a new `Bitmap` object.
Bitmap.new(texture)
texture : (TextureBase or TextureRegion)

Example:
local texture=Texture.new('image.png')

local region=TextureRegion.new(texture, 0, 0, 100, 50)

local bitmap1=Bitmap.new(texture)
local bitmap2=Bitmap.new(region)

stage:addChild(bitmap1)
stage:addChild(bitmap2)

Bitmap : getAnchorPoint 2011.6+


Returns the x and y coordinates of the anchor point.
num, num = Bitmap:getAnchorPoint()
num : The x coordinate of the anchor point.
num : The y coordinate of the anchor point.

Bitmap : setAnchorPoint 2011.6+


Sets the anchor point of `Bitmap` object. Each `Bitmap` object has an anchor point that affects the
positioning of the texture displayed. By modifying the anchor point, you change the origin of the texture. For
example, setting the anchor point to (0.5, 0.5) moves the center of the texture to the origin. If you set the
anchor point to (1, 1) instead, the bottom-right corner of the texture will be the origin. The default value of
anchor point is (0, 0) which means top-left of the texture is the origin by default.
Bitmap:setAnchorPoint(x, y)
x : (num) The x coordinate of anchor point. Usually between [0, 1].
y : (num) The y coordinate of anchor point. Usually between [0, 1].

Bitmap : setTexture 2012.08.2+


Sets the texture.
Bitmap:setTexture(texture)
texture : (TextureBase)

Bitmap : setTextureRegion 2012.08.2+


Sets the texture region.
Bitmap:setTextureRegion(textureRegion)

Gideros API Reference v2017.12 Page 15


textureRegion : (TextureRegion)

Gideros API Reference v2017.12 Page 16


Core Inherits: Object 2012.2+
Gideros Core functions

Example:
MySprite=Core.class(Sprite)
--my custom sprite class
function MySprite:init()
end

Core . asyncCall 2016.06+


Launch function on separate thread as background task.Background threads are only executed when main
thread is not running
Core.asyncCall(task [, parameters])
task : (function) function to run in background
parameters : (multiple) multiple parameters to pass to function

Core . class 2012.2+


Creates and returns new Gideros class
Core.class([base])
base : (GiderosClass) Gideros class from which to inherit

Core . frameStatistics 2016.08+


Returns table with fields: *meanFrameTime* - the average duration of a frame (useful to get current fps),
*meanFreeTime* - the average free cpu time in a frame*frameCounter* - frame's number
table = Core.frameStatistics()
table : table with data

Core . profilerReport 2017.8+


Returns an associative array of tables describing CPU usage of lua functions. Each table in the array is
indexed by an unique function id and has the following content: *name* - Name of the function *time* - Total
time spent in the function (seconds)*count* - Number of times this function was called*callers* - A table
containing the same information has above for each function which called this one
table = Core.profilerReport()
table : table with profiling data

Core . profilerReset 2017.8+


Drop currently recorded data and reset profiler for a clean subsequent start
Core.profilerReset()

Core . profilerStart 2017.8+


Start recording of time spent in each lua function
Core.profilerStart()

Gideros API Reference v2017.12 Page 17


Core . profilerStop 2017.8+
Stop collecting profiling data
Core.profilerStop()

Core . random 2017.9+


Generate and return a pseudo random number. The random number sequence is guaranteed to be
consistent across devices for a given seed. If bounds aren't specified, the function will return a floating point
number between 0 and 1. If one bound is specified, the function will return an integer number between 1 and
that bound (inclusive). If both bounds are specified, the function will return an integer between bound1 and
bound2. bound2 must be greater than bound1.
random number = Core.random([generator] [, bound1] [, bound2])

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

Core . randomSeed 2017.9+


Set the current seed of the specified random number generator.
A seed usable for later resuming the RNG = Core.randomSeed([generator] [, seed])

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

Core . yield 2016.06+


Yield function running as background task.Core.yield([number of seconds to wait])Core.yield(true) -- yield for
a single frame and disable auto yield Core.yield(false) -- don't yield now, but reenable autoyield
Core.yield(state)
state : (number or boolean) number of seconds to yield or boolean to enable/disable auto yield

Gideros API Reference v2017.12 Page 18


Cryptography 2016.04+
Cryptographic primitives

Cryptography . aesDecrypt 2016.04+


Decrypt an AES 128 cipher text, ECB or CBC
str = Cryptography.aesDecrypt(ciphertext, key [, iv] [, paddingType])

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

Cryptography . aesEncrypt 2016.04+


Encrypt a string with AES 128 cipher, either in ECB mode or CBC mode
str = Cryptography.aesEncrypt(plaintext, key [, iv] [, paddingType])

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

Cryptography . md5 2016.04+


Compute the MD5 hash of the input string
str = Cryptography.md5(input)

Parameter:
input : (str) String whose content is to be hashed

Result:
str : MD5 hash (a 16 byte string)

Gideros API Reference v2017.12 Page 19


Event Inherits: Object 2011.6+
The objects of `Event` class contains information about an event that has occurred. `Event` objectsare
passed to event listeners when an event occurs.Usually event objects contains specific additional
information about the event that has occured. For example,when an `Event.MOUSE_DOWN` event occurs,
`x` and `y` fields contain the coordinates.Users can create their own events and dispatch through the event
mechanism.

Mouse down event example


function onMouseDown(event)
print(event.x, event.y)
end
mysprite:addEventListener(Event.MOUSE_DOWN, onMouseDown)

User created event


local event=Event.new('myevent')
event.data1='12345'
event.data2='abcde'
mydispatcher:dispatchEvent(event)

Event . new 2011.6+


Creates a new `Event` object to be dispatched from an `EventDispatcher`.
any, any = Event.new(type)

Parameter:
type : (str)

Results:
any : New `Event` object.
any : New `Event` object.

Event : getTarget 2011.6+


Returns the element on which the event listener was registered.
object = Event:getTarget()
object : Target of event.

Event : getType 2011.6+


Returns a string that represents the type of the event.
str = Event:getType()
str : Type of event.

Event : stopPropagation 2011.6+


Disables the propagation of the current event in the scene tree hierarchy.
Event:stopPropagation()

Gideros API Reference v2017.12 Page 20


EventDispatcher Inherits: Object 2011.6+
All classes that dispatch events inherit from `EventDispatcher`. The target of an event is a listener function
and an optional data value.When an event is dispatched, the registered function is called.If the optional data
value is given, it is used as a first parameter while calling the listener function.Event dispatching and event
targets are the core part of the Gideros event model. Different event types (such as `Event.ENTER_FRAME`,
`Event.TOUCHES_BEGIN` or `Event.MOUSE_DOWN`) flow through the scene tree hierarchy differently.
When a touch or mouse event occurs, Gideros dispatches an event object into the event flow from the root of
the scene tree.On the other hand, `Event.ENTER_FRAME` event is dispatched to all `Sprite` objects.If you
want to define a class that dispatches events, you can inherit your class from `EventDispatcher`.

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

b:addEventListener('myevent', a.funcA, a) -- when b dispatches an 'myevent' event,


-- a.funcA will be called with 'a'
-- as first parameter

b:dispatchEvent(Event.new('myevent')) -- will print 'funcA'

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

EventDispatcher . new 2011.6+


Creates a new EventDispatcher object
EventDispatcher.new()

EventDispatcher : addEventListener 2011.6+


Registers a listener function and an optional data value so that the listener function is called when an eventof
a particular type occurs.
EventDispatcher:addEventListener(type, listener [, data])
type : (str) The type of event.
listener : (function) The listener function that processes the event.

Gideros API Reference v2017.12 Page 21


data : (any) An optional data parameter that is passed as a first argument to the listener function.

EventDispatcher : dispatchEvent 2011.6+


Dispatches an event to this `EventDispatcher` instance.
EventDispatcher:dispatchEvent(event)
event : (Event) The `Event` object to be dispatched.

EventDispatcher : hasEventListener 2011.6+


Checks if the `EventDispatcher` object has a event listener registered for the specified type of event.
bool = EventDispatcher:hasEventListener(type)

Parameter:
type : (str) The type of event.

Result:
bool : A value of `true` if a listener of the specified type is registered; `false` otherwise.

EventDispatcher : removeEventListener 2011.6+


Removes a listener from the `EventDispatcher` object. `removeEventListener()` function expectsthe same
arguments with `addEventListener()` to remove the event. If there is no matching listenerregistered, a call to
this function has no effect.
EventDispatcher:removeEventListener(type, listener, data)
type : (str) The type of event.
listener : (function) The listener object to remove.
data : (any) The data parameter that is used while registering the event.

Gideros API Reference v2017.12 Page 22


Font Inherits: FontBase 2011.6+
The `Font` class is used to load fonts created by "Gideros Font
Creator".![images/font_creator.png]Gideros Font Creator exports two files: A `.txt` file that specifies the
positions of character glyph a `.png` file of font.

Use these two files to create `Font` object as:


local font=Font.new("font.txt", "font.png")

Font . getDefault 2015.08+


Returns Font object used as default font in Gideros
Font.getDefault()

Font . new 2011.6+


Creates a new `Font` object.
Font.new(txtfile, imagefile, filtering)
txtfile : (str)
imagefile : (str)
filtering : (boolean, default = false) Whether or not the font texture is filtered

Gideros API Reference v2017.12 Page 23


FontBase Inherits: Object 2011.6+
`FontBase` is the base class for `Font` and `TTFont` classes.

FontBase : getAdvanceX 2011.6+


Returns the width of the first `size` characters of `text`. Note that this value is not equal to the 3rd return
value (width) of `getBounds()`. `getBounds()` returns a rectangle describing the bounds this string will cover
whereas `getAdvanceX()` returns the distance to where the next string should be drawn.
num = FontBase:getAdvanceX(text, letterSpacing, size)

Parameters:
text : (str)
letterSpacing : (number, default = 0)
size : (number, optional)

Result:
num : The width of the first size characters of text.

FontBase : getAscender 2011.6+


Returns the ascender of the font. The ascender of a font is the distance from the baseline to the highest
position characters extend to.
num = FontBase:getAscender()
num : The ascender of the font

FontBase : getBounds 2011.6+


Returns the tight bounding rectangle of the characters in the string specified by `text`.
num, num, num, num = FontBase:getBounds(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

FontBase : getLineHeight 2011.6+


Returns the distance from one base line to the next.
num = FontBase:getLineHeight()
num : The distance from one base line to the next.

FontBase : layoutText 2017.10+


Compute the layout of the given text according to a given rectangular region size, layout flags and other
parameters.Refer to `TextField:setLayout` for a description of the arguments.The returned table contains
the following fields:- x,y,w,h: Computed bounding box of the full text- lines: The number of lines used to
display the text- parts: Information about individual chunks of texts.Each table in the part field of the returned
table describe the placement of chunks of text. Their fields are:- text: The text to display in this chunk-

Gideros API Reference v2017.12 Page 24


x,y,w,h: Computed bounding box of this chunk - dx,dy: Coordinates to draw this chunk at- sep: separator
character that came just after this chunk in text block- line: line number this chunk belongs to
table = FontBase:layoutText(text, width, height, flags, letterSpacing, lineSpacing, tabSpace)

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.

Gideros API Reference v2017.12 Page 25


Geolocation Inherits: Object 2012.8+
The `Geolocation` class is used to configure the parameters and dispatching of location and heading related
events.

Example:
geolocation=Geolocation.new()

local function onLocationUpdate(event)


print('location: ', event.latitude, event.longitude, event.altitude)
end

local function onHeadingUpdate(event)


print('heading: ', event.magneticHeading, event.trueHeading)
end

geolocation:addEventListener(Event.LOCATION_UPDATE, onLocationUpdate)
geolocation:addEventListener(Event.HEADING_UPDATE, onHeadingUpdate)
geolocation:start()

Geolocation . getAccuracy 2012.8+


Returns the previously set desired accuracy.
num = Geolocation.getAccuracy()
num : The previously set desired accuracy

Geolocation . getThreshold 2012.8+


Returns the previously set minimum distance threshold.
num = Geolocation.getThreshold()
num : The previously set minimum distance threshold

Geolocation . isAvailable 2012.8+


Returns `true` if the device has the capability to determine current location and this capability is enabled,
`false` otherwise.
bool = Geolocation.isAvailable()
bool : `true` if geolocation is available, `false` otherwise

Geolocation . isHeadingAvailable 2012.8+


Returns `true` if the device has the capability to determine heading, `false` otherwise.
bool = Geolocation.isHeadingAvailable()
bool : `true` if heading is available, `false` otherwise

Geolocation . new 2012.8+


Creates new Geolocation instance
Geolocation.new()

Gideros API Reference v2017.12 Page 26


Geolocation . setAccuracy 2012.8+
Sets the desired accuracy (in meters) of the location data. The receiver does its best to achieve the
requested accuracy. However the actual accuracy is not guaranteed. The default value is 0 (best accuracy).
Geolocation.setAccuracy(accuracy)
accuracy : (num) the desired accuracy

Geolocation . setThreshold 2012.8+


Sets the minimum distance (in meters) threshold. If threshold distance is greater than 0, a location event will
only be dispatched if the device moves by threshold. The default value is 0 (as frequently as possible).
Geolocation.setThreshold(threshold)
threshold : (num) the minimum distance threshold

Geolocation : start 2012.8+


Starts the generation of updates that report the current location and heading.
Geolocation:start()

Geolocation : startUpdatingHeading 2012.8+


Starts the generation of updates that report the heading.
Geolocation:startUpdatingHeading()

Geolocation : startUpdatingLocation 2012.8+


Starts the generation of updates that report the current location.
Geolocation:startUpdatingLocation()

Geolocation : stop 2012.8+


Stops the generation of updates that report the current location and heading.
Geolocation:stop()

Geolocation : stopUpdatingHeading 2012.8+


Stops the generation of updates that report the heading.
Geolocation:stopUpdatingHeading()

Geolocation : stopUpdatingLocation 2012.8+


Stops the generation of updates that report the current location.
Geolocation:stopUpdatingLocation()

Gideros API Reference v2017.12 Page 27


Gyroscope Inherits: Object 2012.8+
The `Gyroscope` class is used to access gyroscope data.

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

print(angx*180/math.pi, angy*180/math.pi, angz*180/math.pi)


end

stage:addEventListener('enterFrame', onEnterFrame)

Gyroscope . isAvailable 2012.8+


Returns `true` if gyroscope is available for this platform, `false` otherwise.
bool = Gyroscope.isAvailable()
bool : `true` if gyroscope is available for this platform, `false` otherwise.

Gyroscope . new 2012.8+


Creates new Gyroscope instance
Gyroscope.new()

Gyroscope : getRotationRate 2012.8+


Returns the device's rate of rotation around three axes in radians per second.
num, num, num = Gyroscope:getRotationRate()
num : rate of rotation around x
num : rate of rotation around y
num : rate of rotation around z

Gyroscope : start 2012.8+


Starts the generation of gyroscope samples.
Gyroscope:start()

Gyroscope : stop 2012.8+


Stops the generation of gyroscope samples.

Gideros API Reference v2017.12 Page 28


Gyroscope:stop()

Gideros API Reference v2017.12 Page 29


JS BETA
Run JavaScript code

JS . eval BETA
execute arbitrary Javascript code on HTML5 platform
JS.eval(code)
code : (str) JavaScript code to execute

Gideros API Reference v2017.12 Page 30


KeyCode Inherits: Object 2011.6+
KeyCode table holds the key code constants. These map directly to a physical key on the keyboard.

Listening for back button


stage:addEventListener(Event.KEY_DOWN, function(event)
if event.keyCode == KeyCode.BACK then
application:exit()
end
end)

Gideros API Reference v2017.12 Page 31


Matrix Inherits: Object 2011.6+
The Matrix class specifies transformation from one coordinate space to another.These transformations
include translation, rotation, scaling and skewing.A 2D transformation matrix is a 3 x 3 matrix in
homogenous coordinate system:![images/matrix_props.png]You can get and set the values of all six of the
properties in aMatrix object: `m11`, `m12`, `m21`, `m22`, `tx`, and `ty`.Since Gideros 2016.6, Matrix can
also hold 3D (4x4) matrices.

Applying matrix to Sprite objects


local angle=math.rad(30)
-- create skew matrix
local m=Matrix.new(1, math.tan(angle), math.tan(angle), 1, 0, 0)
--aply to Sprite
local sprite=Sprite.new()
sprite:setMatrix(m)

Matrix . new 2011.6+


Creates a new Matrix object with the specified parameters.
any, any = Matrix.new(m11, m12, m21, m22, tx, ty)

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.

Matrix : getAnchorPosition 2016.06+


get anchor position from matrix transformation
num, num, num = Matrix:getAnchorPosition()
num : x anchor position
num : y anchor position
num : z anchor position

Matrix : getElements 2011.6+


Returns the elements of the matrix.![images/matrix_props.png]
num, num, num, num, num, num = Matrix:getElements()
num : m11 element
num : m12 element
num : m21 element
num : m22 element
num : tx element
num : ty element

Gideros API Reference v2017.12 Page 32


Matrix : getM11 2011.6+
Returns the value of the `m11` component for this `Matrix` instance.
num = Matrix:getM11()
num : The current `m11` parameter.

Matrix : getM12 2011.6+


Returns the value of the `m12` component for this `Matrix` instance.
num = Matrix:getM12()
num : The current `m12` parameter.

Matrix : getM21 2011.6+


Returns the value of the `m21` component for this `Matrix` instance.
num = Matrix:getM21()
num : The current `m21` parameter.

Matrix : getM22 2011.6+


Returns the value of the `m22` component for this `Matrix` instance.
num = Matrix:getM22()
num : The current `m22` parameter.

Matrix : getMatrix 2016.06+


get all 16 elements of 4x4 matrix
num, num, num, num, num, num, num, num, num, num, num, num, num, num, num, num = Matrix:getMatrix()
num : m11
num : m12
num : m13
num : m14
num : m21
num : m22
num : m23
num : m24
num : m31
num : m32
num : m33
num : m34
num : m41
num : m42
num : m43
num : m44

Matrix : getPosition 2016.06+


get position from matrix transformation
num, num, num = Matrix:getPosition()
num : x position

Gideros API Reference v2017.12 Page 33


num : y position
num : z position

Matrix : getRotationX 2016.06+


get rotation for x axis
num = Matrix:getRotationX()
num : rotation on x axis

Matrix : getRotationY 2016.06+


get rotation on y axis
num = Matrix:getRotationY()
num : rotation on y axis

Matrix : getRotationZ 2016.06+


get rotation for z axis
num = Matrix:getRotationZ()
num : rotation around z axis

Matrix : getScale 2016.06+


get scale from matrix transformation
num, num, num = Matrix:getScale()
num : scale on x axis
num : scale on y axis
num : scale on z axis

Matrix : getScaleX 2016.06+


get scale on x axis
num = Matrix:getScaleX()
num : scale on x axis

Matrix : getScaleY 2016.06+


get scale on y axis
num = Matrix:getScaleY()
num : scale on y axis

Matrix : getScaleZ 2016.06+


get scale on z axis
num = Matrix:getScaleZ()
num : scale on z axis

Matrix : getTx 2011.6+

Gideros API Reference v2017.12 Page 34


Returns the value of the `tx` component for this `Matrix` instance.
num = Matrix:getTx()
num : The current `tx` parameter.

Matrix : getTy 2011.6+


Returns the value of the `ty` component for this `Matrix` instance.
num = Matrix:getTy()
num : The current `ty` parameter.

Matrix : getTz 2016.06+


Returns the value of the `tz` component for this `Matrix` instance.
num = Matrix:getTz()
num : The current `tz` parameter.

Matrix : getX 2016.06+


get x position
num = Matrix:getX()
num : x position

Matrix : getY 2016.06+


get y position
num = Matrix:getY()
num : y position

Matrix : getZ 2016.06+


get z position
num = Matrix:getZ()
num : z position

Matrix : invert BETA


Inverts the matrix
Matrix:invert()

Matrix : multiply 2016.06+


Multiply current matrix with new one
Matrix:multiply(matrix)
matrix : (Matrix) matrix with which to multiply current matrix

Matrix : orthographicProjection 2016.06+


Replace this matrix by an orthographic projection suitable for the current 3D engine

Gideros API Reference v2017.12 Page 35


Matrix:orthographicProjection(left, right, bottom, top, near, far)
left : (num) left plane distance
right : (num) right plane distance
bottom : (num) bottom plane distance
top : (num) top plane distance
near : (num) near plane distance
far : (num) far plane distance

Matrix : perspectiveProjection 2016.06+


replace this matrix by a perspective projection matrix suitable for the current 3D engine
Matrix:perspectiveProjection(left, right, bottom, top, near, far)
left : (num) left plane distance
right : (num) right plane distance
bottom : (num) bottom plane distance
top : (num) top plane distance
near : (num) near plane distance
far : (num) far plane distance

Matrix : perspectiveProjection 2016.06+


replace this matrix by a perspective projection matrix suitable for this 3D engine (simplified form)
Matrix:perspectiveProjection(fov, aspect, near, far)
fov : (num) field of view angle
aspect : (num) aspect ratio (width/height)
near : (num) near plane distance
far : (num) far plane distance

Matrix : perspectiveProjection 2016.06+


replace this matrix by a perspective projection matrix suitable for the current 3D engine
Matrix:perspectiveProjection(left, right, bottom, top, near, far)
left : (num) left plane distance
right : (num) right plane distance
bottom : (num) bottom plane distance
top : (num) top plane distance
near : (num) near plane distance
far : (num) far plane distance

Matrix : perspectiveProjection 2016.06+


replace this matrix by a perspective projection matrix suitable for this 3D engine (simplified form)
Matrix:perspectiveProjection(fov, aspect, near, far)
fov : (num) field of view angle
aspect : (num) aspect ratio (width/height)
near : (num) near plane distance
far : (num) far plane distance

Matrix : rotate 2016.06+

Gideros API Reference v2017.12 Page 36


Combine existing rotation with provided.It takes a x,y,z vector and an angle, and rotate the matrix around the
given vector by the specified angle
Matrix:rotate(angle, x vector, y vector, z vector)
angle : (num) angle of rotation in radians
x vector : (num) x axis vector
y vector : (num) y axis vector
z vector : (num) z axis vector

Matrix : scale 2016.06+


combine existing scale with provided scale
Matrix:scale(x scale [, y scale] [, z scale])
x scale : (num) scale on x axis
y scale : (num) scale on y axis
z scale : (num) scale on z axis

Matrix : setAnchorPosition 2016.06+


transform matrix for setting anchor position
Matrix:setAnchorPosition(x, y [, z])
x : (num) x anchor position
y : (num) y anchor position
z : (num) z anchor position

Matrix : setElements 2011.6+


Sets all 6 elements of the matrix.
Matrix:setElements(m11, m12, m21, m22, tx, ty)
m11 : (number, default = 1)
m12 : (number, default = 0)
m21 : (number, default = 0)
m22 : (number, default = 1)
tx : (number, default = 0)
ty : (number, default = 0)

Matrix : setM11 2011.6+


Sets the value of the `m11` component for this `Matrix` instance.
Matrix:setM11(m11)
m11 : (num)

Matrix : setM12 2011.6+


Sets the value of the `m12` component for this `Matrix` instance.
Matrix:setM12(m12)
m12 : (num)

Matrix : setM21 2011.6+

Gideros API Reference v2017.12 Page 37


Sets the value of the `m21` component for this `Matrix` instance.
Matrix:setM21(m21)
m21 : (num)

Matrix : setM22 2011.6+


Sets the value of the `m22` component for this `Matrix` instance.
Matrix:setM22(m22)
m22 : (num)

Matrix : setMatrix 2016.06+


set all 16 elements of 4x4 matrix
Matrix:setMatrix([m11] [, m12] [, m13] [, m14] [, m21] [, m22] [, m23] [, m24] [, m31] [, m32] [, m33] [, m34] [, m41] [
, m42] [, m43] [, m44])
m11 : (num)
m12 : (num)
m13 : (num)
m14 : (num)
m21 : (num)
m22 : (num)
m23 : (num)
m24 : (num)
m31 : (num)
m32 : (num)
m33 : (num)
m34 : (num)
m41 : (num)
m42 : (num)
m43 : (num)
m44 : (num)

Matrix : setPosition 2016.06+


transform matrix for setting position
Matrix:setPosition(x, y [, z])
x : (num) x position
y : (num) y position
z : (num) z position

Matrix : setRotationX 2016.06+


set rotation on x axis
Matrix:setRotationX(x rotation)
x rotation : (num) rotation on x axis

Matrix : setRotationY 2016.06+


set rotation on y axis
Matrix:setRotationY(y rotation)

Gideros API Reference v2017.12 Page 38


y rotation : (num) rotation on y axis

Matrix : setRotationZ 2016.06+


set rotation on z axis
Matrix:setRotationZ(z rotation)
z rotation : (num) rotation on z axis

Matrix : setScale 2016.06+


transform matrix for setting scale
Matrix:setScale(x [, y] [, z])
x : (num) scale on x axis
y : (num) scale on y axis
z : (num) scale on z axis

Matrix : setScaleX 2016.06+


set scale on x axis
Matrix:setScaleX(x scale)
x scale : (num) scale on x axis

Matrix : setScaleY 2016.06+


set scale on y axis
Matrix:setScaleY(y scale)
y scale : (num) set scale on y axis

Matrix : setScaleZ 2016.06+


set scale on z axis
Matrix:setScaleZ(z scale)
z scale : (num) scale on z axis

Matrix : setTx 2011.6+


Sets the value of the `tx` component for this `Matrix` instance.
Matrix:setTx(tx)
tx : (num)

Matrix : setTy 2011.6+


Sets the value of the `ty` component for this `Matrix` instance.
Matrix:setTy(ty)
ty : (num)

Matrix : setTz 2016.06+

Gideros API Reference v2017.12 Page 39


Sets the value of the `tz` component for this `Matrix` instance.
Matrix:setTz(tz)
tz : (num)

Matrix : setX 2016.06+


set x position
Matrix:setX(x)
x : (num) x position

Matrix : setY 2016.06+


set y position
Matrix:setY(y)
y : (num) y position

Matrix : setZ 2016.06+


set z position
Matrix:setZ(z)
z : (num) z position

Matrix : transformPoint BETA


Transforms the matrix
Matrix:transformPoint()

Matrix : translate 2016.06+


combine existing translation with provided translation
Matrix:translate(x [, y] [, z])
x : (num) translate on x axis
y : (num) translate on y axis
z : (num) translate on z axis

Gideros API Reference v2017.12 Page 40


Mesh Inherits: Sprite 2012.09+
Mesh class is used to create and display custom constructed set of triangles (triangle meshes). It basically
consists of4 arrays: vertex, index, color (optional), textureCoordinate (optional) and a texture (optional) and it
provides more thanone way to set/modify these arrays.Mesh can be 2D or 3D, the latter expects an
additionnal Z coordinate in its vertices. Additionnally, 3D meshes and their children are rendered with depth
testing enabled, which prevents far objects to be drawn above nearest ones, irrespective of actual drawing
order.<ul><li>`Note 1:` Mesh class doesn't do bounds check. If an element at index array points to an
non-existent vertex, the application may crash.</li></ul>

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)

-- 1. triangle from 1, 2 and 3 vertex


-- 2. triangle from 1, 3 and 4 vertex
mesh:setIndexArray(1, 2, 3, 1, 3, 4)

-- 1. vertex 0xff0000 color with 0.5 alpha


-- 2. vertex 0x00ff00 color with 0.7 alpha
-- 3. vertex 0x0000ff color with 1 alpha
-- 4. vertex 0xffff00 color with 0 alpha
mesh:setColorArray(0xff0000, 0.5, 0x00ff00, 0.7, 0x0000ff, 1.0, 0xffff00, 0)

Mesh . new 2015.04.04+


Creates a new `Mesh` object.
Mesh.new([is3d])
is3d : (bool) Specifies that this mesh expect Z coordinate in its vertex array and is thus a 3D mesh

Mesh : clearColorArray 2012.09+


Clears the color array.
Mesh:clearColorArray()

Mesh : clearIndexArray 2012.09+


Clears the index array.
Mesh:clearIndexArray()

Mesh : clearTexture 2012.09+


Clears the texture. By default the texture at slot 0 is cleared. To clear a particular texture, pass its slot number
to this method
Mesh:clearTexture([slot])
slot : (num) The slot number of the texture to clear. If no argument is provided, slot=0 is assumed

Gideros API Reference v2017.12 Page 41


Mesh : clearTextureCoordinateArray 2012.09+
Clears the texture coordinate array.
Mesh:clearTextureCoordinateArray()

Mesh : clearVertexArray 2012.09+


Clears the vertex array.
Mesh:clearVertexArray()

Mesh : getColor 2013.06+


Returns color and alpha of the i-th element from color array
num, num = Mesh:getColor(i)

Parameter:
i : (num) index

Results:
num : color
num : normalizes alpha (0-1)

Mesh : getColorArraySize 2013.06+


Get size of the Color array
num = Mesh:getColorArraySize()
num : size of color array

Mesh : getIndex 2013.06+


Returns the i-th element from index array
num = Mesh:getIndex(i)

Parameter:
i : (num) index

Result:
num : index of element

Mesh : getIndexArraySize 2013.06+


Get size of the Index array
num = Mesh:getIndexArraySize()
num : size of index array

Mesh : getTextureCoordinate 2013.06+


Returns u and v coordinate of the i-th element from texture coordinate array
num, num = Mesh:getTextureCoordinate(i)

Parameter:
i : (num) index

Gideros API Reference v2017.12 Page 42


Results:
num : u coordinate
num : v cordinate

Mesh : getTextureCoordinateArraySize 2013.06+


Get size of the Texture Coordinate array
num = Mesh:getTextureCoordinateArraySize()
num : size of coordinate array

Mesh : getVertex 2013.06+


Returns x and y coordinate of the i-th element from vertex array
num, num = Mesh:getVertex(i)

Parameter:
i : (num) index

Results:
num : x coordinate of vertex
num : y coordinate of vertex

Mesh : getVertexArraySize 2013.06+


Get size of the Vertices array
num = Mesh:getVertexArraySize()
num : size of vertex array

Mesh : resizeColorArray 2012.09+


Resizes the color array to contain `size` elements.If `size` is smaller than the current color array size, the
content is reduced to its first `size` elements, the rest being dropped.If `size` is greater than the current color
array size, the content is expanded by inserting at the end as many copies of 0s as needed to reach a size of
`size` elements.
Mesh:resizeColorArray(size)
size : (num) new color array size

Mesh : resizeIndexArray 2012.09+


Resizes the index array to contain `size` elements.If `size` is smaller than the current index array size, the
content is reduced to its first `size` elements, the rest being dropped.If `size` is greater than the current
index array size, the content is expanded by inserting at the end as many copies of 0s as needed to reach a
size of `size` elements.
Mesh:resizeIndexArray(size)
size : (num) new index array size

Mesh : resizeTextureCoordinateArray 2012.09+


Resizes the texture coordinate array to contain `size` elements.If `size` is smaller than the current texture
coordinate array size, the content is reduced to its first `size` elements, the rest being dropped.If `size` is
greater than the current texture coordinate array size, the content is expanded by inserting at the end as

Gideros API Reference v2017.12 Page 43


many copies of 0s as needed to reach a size of `size` elements.
Mesh:resizeTextureCoordinateArray(size)
size : (num) new texture coordinate array size

Mesh : resizeVertexArray 2012.09+


Resizes the vertex array to contain `size` elements.If `size` is smaller than the current vertex array size, the
content is reduced to its first `size` elements, the rest being dropped.If `size` is greater than the current
vertex array size, the content is expanded by inserting at the end as many copies of 0s as needed to reach a
size of `size` elements.
Mesh:resizeVertexArray(size)
size : (num) new vertex array size

Mesh : setColor 2012.09+


Sets a color at color array. Indices are start from 1. If the color array is not large enough, it's expanded
automatically.
Mesh:setColor(i, color, alpha)
i : (num) index
color : (num) color in hexedecial value
alpha : (number, default=1.0) alpha value

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

Mesh : setColorArray 2012.09+


Assigns new content to the color array, dropping all the elements contained in the color array before the call
and replacing them by those specified by the parameters. It accepts multiple values or a Lua array.
Mesh:setColorArray(colors)
colors : (any)

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}

Mesh : setColors 2012.09+


Sets zero or more colors at color array with a single function call. It accepts multiple values or a Lua array.
Mesh:setColors(colors)
colors : (any)

Example:
-- set 3 colors with seperate function calls

Gideros API Reference v2017.12 Page 44


mesh:setColor(1, 0xff0000, 0.5)
mesh:setColor(2, 0x00ff00, 0.7)
mesh:setColor(3, 0x0000ff)

-- set 3 colors with one function call


mesh:setColors(1, 0xff0000, 0.5, 2, 0x00ff00, 0.7, 3, 0x0000ff, 1.0)

-- same as above
mesh:setColors{1, 0xff0000, 0.5, 2, 0x00ff00, 0.7, 3, 0x0000ff, 1.0}

-- these two functions do nothing


mesh:setColors()
mesh:setColors{}

Mesh : setGenericArray 2017.4+


Assigns new content to a generic additional array to be used by a shader. It accepts multiple values or a Lua
array.
Mesh:setGenericArray(index, type, mult, count, data)
index : (num) The data attribute index in the corresponding shader
type : (num) The data type, one of Shader.Dxxx constants
mult : (num) The vector dimension (1 for simple values, 2 for a vec2/float2, etc)
count : (num) The number of elements in the array
data : (any) The actual values

Mesh : setIndex 2012.09+


Sets a index at index array. Indices are start from 1. If the index array is not large enough, it's expanded
automatically.
Mesh:setIndex(i, index)
i : (num) index
index : (num) index

Example:
-- set the first 3 indices as 10, 11 and 12.
mesh:setIndex(1, 10)
mesh:setIndex(2, 11)
mesh:setIndex(3, 12)

Mesh : setIndexArray 2012.09+


Assigns new content to the index array, dropping all the elements contained in the index array before the call
and replacing them by those specified by the parameters. It accepts multiple values or a Lua array.
Mesh:setIndexArray(indices)
indices : (any)

Example:
-- set the index array as 10, 11 and 12.
mesh:setIndexArray(10, 11, 12)

-- same as above

Gideros API Reference v2017.12 Page 45


mesh:setIndexArray{10, 11, 12}

Mesh : setIndices 2012.09+


Sets zero or more indices at index array with a single function call. It accepts multiple values or a Lua array.
Mesh:setIndices(indices)
indices : (any)

Example:
-- set 3 indices with seperate function calls
mesh:setIndex(1, 10)
mesh:setIndex(2, 11)
mesh:setIndex(3, 12)

-- set 3 indices with one function call


mesh:setIndices(1, 10, 2, 11, 3, 12)

-- same as above
mesh:setIndices{1, 10, 2, 11, 3, 12}

-- these two functions do nothing


mesh:setIndices()
mesh:setIndices{}

Mesh : setTexture 2012.09+


Sets the texture.
Mesh:setTexture(texture [, slot])
texture : (TextureBase)
slot : (num) The slot number which we are adding the Texture to (Meshes can have multiple Textures, one
per slot). If omitted, slot=0 is assumed

Mesh : setTextureCoordinate 2012.09+


Sets a texture coordinate at texture coordinate array. Indices are start from 1. If the texture coordinate array
is not large enough, it's expanded automatically.
Mesh:setTextureCoordinate(i, u, v)
i : (num) index
u : (num) u coordinate
v : (num) v coordinate

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)

Mesh : setTextureCoordinateArray 2012.09+


Assigns new content to the texture coordinate array, dropping all the elements contained in the texture
coordinate array before the call and replacing them by those specified by the parameters. It accepts multiple

Gideros API Reference v2017.12 Page 46


values or a Lua array.
Mesh:setTextureCoordinateArray(textureCoordinates)
textureCoordinates : (any)

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 2012.09+

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)

-- set 3 texture coordinates with one function call


mesh:setTextureCoordinates(1, 0, 0, 2, 100, 0, 3, 0, 100)

-- same as above
mesh:setTextureCoordinates{1, 0, 0, 2, 100, 0, 3, 0, 100}

-- these two functions do nothing


mesh:setTextureCoordinates()
mesh:setTextureCoordinates{}

Mesh : setVertex 2012.09+


Sets a vertex at vertex array. Indices are start from 1. If the vertex array is not large enough, it's expanded
automatically.
Mesh:setVertex(i, x, y)
i : (num) index
x : (num) x coordinate
y : (num) y coordinate

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)

Mesh : setVertexArray 2012.09+

Gideros API Reference v2017.12 Page 47


Assigns new content to the vertex array, dropping all the elements contained in the vertex array before the
call and replacing them by those specified by the parameters. It accepts multiple values or a Lua array.
Mesh:setVertexArray(vertices)
vertices : (any)

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}

Mesh : setVertices 2012.09+


Sets zero or more vertices at vertex array with a single function call. It accepts multiple values or a Lua array.
Mesh:setVertices(vertices)
vertices : (any)

Example:
-- set 3 vertices with seperate function calls
mesh:setVertex(1, 100, 100)
mesh:setVertex(2, 150, 100)
mesh:setVertex(3, 100, 150)

-- set 3 vertices with one function call


mesh:setVertices(1, 100, 100, 2, 150, 100, 3, 100, 150)

-- same as above
mesh:setVertices{1, 100, 100, 2, 150, 100, 3, 100, 150}

-- these two functions do nothing


mesh:setVertices()
mesh:setVertices{}

Gideros API Reference v2017.12 Page 48


MovieClip Inherits: Sprite 2011.6+
The `MovieClip` class inherits from the following classes: `Sprite` > `EventDispatcher`.The `MovieClip` class
is used create static timedlined animations. The timeline parameters are given as an array. Each array
element specifies one timeline element and consists of the starting frame, ending frame, sprite and optional
tweening parameters. Frame numbers start from 1.When a `MovieClip` object finishes it playing (by
reaching its final frame or a frame with stop action), it dispatches an `Event.COMPLETE` event.The
following properties can be
tweened:<ul><li>`x`</li><li>`y`</li><li>`rotation`</li><li>`scale`</li><li>`scaleX`</li><li>`scaleY`</li><li>`alph
a`</li></ul>Additionally `MovieClip` uses set function to tween properties, so if you override provided object's
set function by adding new parameters it can accept, then you can tween those new parameters too.<br
/>The following easing functions can be used: * `'inBack'` * `'outBack'` * `'inOutBack'` * `'inBounce'` *
`'outBounce'` * `'inOutBounce'` * `'inCircular'` * `'outCircular'` * `'inOutCircular'` * `'inCubic'` * `'outCubic'` *
`'inOutCubic'` * `'inElastic'` * `'outElastic'` * `'inOutElastic'` * `'inExponential'` * `'outExponential'` *
`'inOutExponential'` * `'linear'` * `'inQuadratic'` * `'outQuadratic'` * `'inOutQuadratic'` * `'inQuartic'` *
`'outQuartic'` * `'inOutQuartic'` * `'inQuintic'` * `'outQuintic'` * `'inOutQuintic'` * `'inSine'` * `'outSine'` *
`'inOutSine'`Following examples demonstrates the possible uses of MovieClip class.

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 100 frame animation where x coordinate of sprite is 50 (constant) and


-- y coordinate of sprite tweens from 50 to 150 by using inBounce function
local mc=MovieClip.new{
{1, 100, sprite, {x=50, y={50, 150, "inBounce"}}}
}

-- 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 where each frame is a different sprite


local mc=MovieClip.new{
{1, 1, frame1},
{2, 2, frame2},
{3, 3, frame3},
{4, 4, frame4},
{5, 5, frame5},
{6, 6, frame6},
}
mc:setGotoAction(6, 1) -- if the animation reaches frame 6 then go to frame 1

-- construct a looping 6 frame animation playing 5 times slower than the previous example
local mc=MovieClip.new{
{1, 5, frame1},

Gideros API Reference v2017.12 Page 49


{5, 10, frame2},
{11, 15, frame3},
{16, 20, frame4},
{21, 25, frame5},
{26, 30, frame6},
}
mc:setGotoAction(30, 1) -- if the animation reaches frame 30 then go to frame 1

MovieClip . new 2011.6+


Creates a new `MovieClip` object. After constructing the MovieClip object, it starts playing. You don't need
tocall [[MovieClip:play]].
MovieClip.new(timeline)
timeline : (table) array of timeline elements

MovieClip : clearAction 2011.6+


Clears the action (goto or stop) at the specified frame.
MovieClip:clearAction(frame)
frame : (int) the frame number

MovieClip : gotoAndPlay 2011.6+


Goes to the specified frame and starts playing.
MovieClip:gotoAndPlay(frame)
frame : (int) the frame number

MovieClip : gotoAndStop 2011.6+


Goes to the specified frame and stops.
MovieClip:gotoAndStop(frame)
frame : (int) the frame number

MovieClip : play 2011.6+


Starts playing the movie clip.
MovieClip:play()

MovieClip : setGotoAction 2011.6+


Sets a *goto* action to the specified frame. When the movie clip reaches a frame with goto action, it jumps to
the destination frame and continues to play. This function is usually used to create looping animations.
MovieClip:setGotoAction(frame, destframe)
frame : (int) the frame number
destframe : (int) the destination frame number

MovieClip : setStopAction 2011.6+


Sets a *stop* action to the specified frame. When the movie clip reaches a frame with stop action, it stops

Gideros API Reference v2017.12 Page 50


playing. This function is usually used to dividethe animation into independent parts.
MovieClip:setStopAction(frame)
frame : (int) the frame number

MovieClip : stop 2011.6+


Stops playing the movie clip.
MovieClip:stop()

Gideros API Reference v2017.12 Page 51


Object 2015.08+
Main Object class from which all Gideros classes inherit.There is no other purpose for this classes, rather a
neat way to add methods to all Gideros classes

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

Object : getBaseClass 2015.08+


Returns the class name which object directly inherits from
str = Object:getBaseClass()
str : returns base class name

Object : getClass 2015.08+


Returns the class name of the instance as string
str = Object:getClass()
str : class name as string

Object : isInstanceOf 2015.08+


Returns true if instance is of provided class name or if it inherits from provided class name
bool = Object:isInstanceOf(classname)

Parameter:
classname : (str) The name of the class to check relation to

Result:
bool : true if instance belongs or inherits from class, false otherwise

Gideros API Reference v2017.12 Page 52


Particles Inherits: Sprite 2016.06+
Particles sprite (alpha), which allows to draw several identical dots or bitmaps with varying colour and
orientation

Particles . new 2016.06+


Create new particles group
Particles.new()

Particles : addParticles 2016.06+


Add particle a single particle (short form) or several ones (long form) to this particle system.Short form
(single particle):`particles:addParticles(x,y,size,angle,ttl)`Extended
form:`particles:addParticles{particleDesc1,particleDesc2,...,particleDescN}`where particleDescX is a table
describing a particle to be added. This table can contain the following parameters:<ul><li>x,y: particle
position</li><li>size: particle size</li><li>angle: particle orientation</li><li>color: particle color</li><li>alpha:
particle alpha</li><li>ttl: time to leave, number of frames this particle will stay on screen</li><li>tag: tag
associated with this particle</li><li>speedX,speedY,speedAngular,speedGrowth: Amount added to x,y,angle
and size at the beginning of each frame</li><li>decay,decayAngular,decayGrowth,decayAlpha: factor applied
to speedX and speedY, speedAngular, speedGrowth and alpha at the beginning of each frame</li></ul>
number or table = Particles:addParticles(particles)

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

Particles : clearTexture 2016.06+


Clear texture for all particles
Particles:clearTexture()

Particles : getParticleAngle 2016.06+


get particle angle
num = Particles:getParticleAngle(i)

Parameter:
i : (num) index of particle

Result:
num : angle of particle in degrees

Particles : getParticleColor 2016.06+


Get color and alpha value of particle
color, alpha = Particles:getParticleColor(i)

Parameter:
i : (num) particle index

Results:

Gideros API Reference v2017.12 Page 53


color : color value
alpha : alpha value from 0 to 1

Particles : getParticleDecay BETA


Get decay values for the given particle
num, num, num, num = Particles:getParticleDecay(i)

Parameter:
i : (num) particle index

Results:
num : speed decay factor
num : alpha decay factor
num : growth speed decay factor
num : angular speed decay factor

Particles : getParticlePosition 2016.06+


get position of particle
num, num = Particles:getParticlePosition(i)

Parameter:
i : (num) index of particle

Results:
num : x position
num : y position

Particles : getParticles BETA


Retrieve particles states of this system
table = Particles:getParticles([set] [, tag])

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

Particles : getParticleSize 2016.06+


get size of particle in pixels
num = Particles:getParticleSize(i)

Parameter:
i : (num) index of particle

Result:
num : size in pixels

Particles : getParticleSpeed 2016.06+


Get speed of particle

Gideros API Reference v2017.12 Page 54


num, num, num, num = Particles:getParticleSpeed(i)

Parameter:
i : (num) particle index

Results:
num : x vector
num : y vector
num : angular velocity
num : growth speed

Particles : getParticleTag BETA


returns the tag associated to the given particle
str = Particles:getParticleTag(i)

Parameter:
i : (num) particle index

Result:
str : tag

Particles : getParticleTtl 2016.06+


get initial time to live of particle
num = Particles:getParticleTtl(i)

Parameter:
i : (num) index of particle

Result:
num : initial time to live in seconds

Particles : isPaused BETA


Returns wether this particle system is paused or not
bool = Particles:isPaused()
bool : true when paused

Particles : removeParticles 2016.06+


Remove particles by index in table or as argumentsremove all particles`particles:removeParticles()`or remove
specific partilces:`particles:removeParticles({1,2,3})`or`particles:removeParticles(1,2,3)`
Particles:removeParticles(particle indeces)
particle indeces : (table or arguments) table or arguments of indexes to remove

Particles : setParticleAngle 2016.06+


set angle of particle
Particles:setParticleAngle(i, angle)
i : (num) index of particle
angle : (num) angle in degrees

Gideros API Reference v2017.12 Page 55


Particles : setParticleColor 2016.06+
set color of particles
Particles:setParticleColor(i, color [, alpha])
i : (num) particle index
color : (num) hex value of color
alpha : (num) alpha value from 0 to 1, default 1

Particles : setParticleDecay BETA


Configure decay values for the given particle
Particles:setParticleDecay(i, decay, decayAlpha, decayGrowth, decayAngular)
i : (num) particle index
decay : (num) speed decay factor
decayAlpha : (num) alpha decay factor
decayGrowth : (num) growth speed decay factor
decayAngular : (num) angular speed decay factor

Particles : setParticlePosition 2016.06+


set position of particle
Particles:setParticlePosition(i, x, y)
i : (num) index of particle
x : (num) x position
y : (num) y position

Particles : setParticleSize 2016.06+


set size of particle
Particles:setParticleSize(i, size)
i : (num) index of particle
size : (num) size of particle in pixels

Particles : setParticleSpeed 2016.06+


Set speed of particles
Particles:setParticleSpeed(i [, x] [, y] [, a] [, s])
i : (num) particle index
x : (num) x vector
y : (num) y vector
a : (num) angular velocity
s : (num) growth speed

Particles : setParticlesTag BETA


set the tag associated to the given particle
Particles:setParticlesTag()

Particles : setParticleTag BETA

Gideros API Reference v2017.12 Page 56


set the tag associated to the given particle.
Particles:setParticleTag(i, tag)
i : (num) particle index
tag : (str) tag to associate to this particle

Particles : setParticleTtl 2016.06+


set time to live
Particles:setParticleTtl(i, ttl)
i : (num) index of particle
ttl : (num) time to live in seconds

Particles : setPaused BETA


Pause or resume this particle system
Particles:setPaused(paused)
paused : (bool) true to pause the particle system, false to resume

Particles : setTexture 2016.06+


Set texture to all particles
Particles:setTexture(texture)
texture : (TextureBase) texture to use in particles

Gideros API Reference v2017.12 Page 57


Path2D Inherits: Sprite 2016.04+
Draw quick 2D vector paths. This class aims at being a faster alternative to Shape for complex/curvy shapes.

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)

Path2D . new 2016.04+


Creates Path2D object
Path2D.new()

Path2D : setConvex 2016.04+


Flag this shape as convex. Convex shapes can be rendered faster.
Path2D:setConvex(convex)
convex : (bool) true if convex

Path2D : setFillColor 2016.04+


Sets fill color
Path2D:setFillColor(color [, alpha])
color : (hex) color to use
alpha : (num) opacity of fill from 0 to 1, default 1

Path2D : setFontPath 2016.04+


Sets the path from the outline of a character in a TTFont.
Path2D:setFontPath(font, character)

Gideros API Reference v2017.12 Page 58


font : (TTFont) Vector font to use
character : (str) character to use from font

Path2D : setLineColor 2016.04+


Sets line color
Path2D:setLineColor(color [, alpha])
color : (hex) color to use
alpha : (num) opacity of line from 0 to 1, default 1

Path2D : setLineThickness 2016.04+


Sets the thickness (width) of the outline, and optionnally set the amount of 'feather' effect.
Path2D:setLineThickness(thickness [, feather])
thickness : (num) line thickness in sprite coordinates units
feather : (num) Sets the amount of 'feather' effect, i.e. the ratio of the line thickness that will be blurred with
background. Values range from 0 (sharp edges) to 1.

Path2D : setPath 2016.04+


Set path to draw, using string with commands represented as:<ul><li>M - MoveTo, 2 values (x,y)</li><li>L -
LineTo, 2 values (x,y)</li><li>Q - QuadTo, 4 values (c0x,c0y,x,y)</li><li>C - CubicTo, 6 values
(c0x,c0y,c1x,c1y,x,y)</li><li>H - Horzontal Line, 1 value (x)</li><li>V - Vertical Line, 1 value (y)</li><li>A -
ArcTo, 7 values (r1,r2,angle,largeArc,sweep,x,y)</li><li>Z - Close, no parameter</li><li>* - repeat last
command until all coordinates are exhausted</li></ul>and provided coordinates as table or simply arguments
Path2D:setPath(commands, coordinates [, more coordinates])
commands : (str) list of commands as ML**Z expecting according coordinates
coordinates : (table or number) lua table with coordinates for each command, in the same order as commands
more coordinates : (num) if second argument is not table, you can provide more coordinates as separate
arguments

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)

Path2D : setSvgPath 2016.04+


Set path with svg properties in single string separated by comma (,)
Path2D:setSvgPath(svg_params)
svg_params : (str) svg params separated by comma

Drawing banana

Gideros API Reference v2017.12 Page 59


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

Path2D : setTexture 2016.04+


Sets texture for fill and optionally apply transformation matrix to it.
Path2D:setTexture(texture [, matrix])
texture : (TextureBase) texture to use as fill
matrix : (Matrix) transformation matrix for texture

Gideros API Reference v2017.12 Page 60


Pixel Inherits: Sprite 2016.06+
A rectangular Sprite which can be filled with solid colors, gradients or textures.Pixel aims at being a simpler
and faster alternative to Shape when needing to display a coloured box or box with a gradient. It is also
useful as Bitmap replacement since every texture will be fitted into Pixel dimensions automatically.

Pixel . new 2016.06+


Create new pixel
Pixel.new([color] [, alpha] [, width] [, height])
color : (num) hex value representing color
alpha : (num) alpha value from 0 to 1
width : (num) width of pixel
height : (num) height of pixel

Pixel . new BETA


Constructor to create a Pixel with texture in letterbox mode. Every texture will be fitted into Pixel dimensions
with preserving texture aspect ratio.
Pixel.new(texture [, width] [, height] [, texture_scale_x] [, texture_scale_y] [, texture_x] [, texture_y])
texture : (Texture) texture to use for the pixel
width : (num) width of the Pixel
height : (num) height of the Pixel
texture_scale_x : (num) horizontal scale of the pixel texture
texture_scale_y : (num) vertical scale of the pixel texture
texture_x : (num) horizontal position of the pixel texture
texture_y : (num) vertical position of the pixel texture

Pixel . new 2016.06+


Create new pixel
Pixel.new([color] [, alpha] [, width] [, height])
color : (num) hex value representing color
alpha : (num) alpha value from 0 to 1
width : (num) width of pixel
height : (num) height of pixel

Pixel . new BETA


Constructor to create a Pixel with texture in letterbox mode. Every texture will be fitted into Pixel dimensions
with preserving texture aspect ratio.
Pixel.new(texture [, width] [, height] [, texture_scale_x] [, texture_scale_y] [, texture_x] [, texture_y])
texture : (Texture) texture to use for the pixel
width : (num) width of the Pixel
height : (num) height of the Pixel
texture_scale_x : (num) horizontal scale of the pixel texture
texture_scale_y : (num) vertical scale of the pixel texture
texture_x : (num) horizontal position of the pixel texture
texture_y : (num) vertical position of the pixel texture

Gideros API Reference v2017.12 Page 61


Pixel : getColor 2016.06+
Gets the color of the Pixel or 4 color-alpha pairs if it has a gradient.
num, num = Pixel:getColor()
num : Color
num : alpha

Pixel : getDimensions BETA


Return the width and height of the Pixel
num, num = Pixel:getDimensions()
num : The Pixel's width
num : The Pixel's height

Pixel : getTexturePosition BETA


Returns the texture position for the Pixel
num, num = Pixel:getTexturePosition()
num : The x-coordinate of the texture
num : The y-coordinate of the texture

Pixel : getTextureScale BETA


Returns the texture scale for the Pixel
num, num = Pixel:getTextureScale()
num : The x-scale of the texture
num : The y-scale of the texture

Pixel : setColor 2016.06+


Sets the color of the Pixel
Pixel:setColor([color] [, alpha])
color : (num) new color
alpha : (num) New alpha value

Pixel : setColor 2011.6+


Sets two-colour gradient fill with optional rotation to Pixel.
Pixel:setColor(color1, alpha1, color2, alpha2 [, angle])
color1 : (num) First color of the gradient.
alpha1 : (num) First alpha of the gradient.
color2 : (num) Second color of the gradient.
alpha2 : (num) Second alpha of the gradient.
angle : (num) Sets rotation of the gradient in degrees. Default value is 270: top-bottom gradient.

Pixel : setColor 2011.6+


Sets 4-colour gradient fill to Pixel.
Pixel:setColor(color1, alpha1, color2, alpha2, color3, alpha3, color4, alpha4)

Gideros API Reference v2017.12 Page 62


color1 : (num) Color of top-left gradient corner.
alpha1 : (num) Alpha of top-left gradient corner.
color2 : (num) Color of top-right gradient corner.
alpha2 : (num) Alpha of top-right gradient corner.
color3 : (num) Color of bottom-right gradient corner.
alpha3 : (num) Alpha of bottom-right gradient corner.
color4 : (num) Color of bottom-left gradient corner.
alpha4 : (num) Alpha of bottom-left gradient corner.

Pixel : setColor 2016.06+


Sets the color of the Pixel
Pixel:setColor([color] [, alpha])
color : (num) new color
alpha : (num) New alpha value

Pixel : setColor 2011.6+


Sets two-colour gradient fill with optional rotation to Pixel.
Pixel:setColor(color1, alpha1, color2, alpha2 [, angle])
color1 : (num) First color of the gradient.
alpha1 : (num) First alpha of the gradient.
color2 : (num) Second color of the gradient.
alpha2 : (num) Second alpha of the gradient.
angle : (num) Sets rotation of the gradient in degrees. Default value is 270: top-bottom gradient.

Pixel : setColor 2011.6+


Sets 4-colour gradient fill to Pixel.
Pixel:setColor(color1, alpha1, color2, alpha2, color3, alpha3, color4, alpha4)
color1 : (num) Color of top-left gradient corner.
alpha1 : (num) Alpha of top-left gradient corner.
color2 : (num) Color of top-right gradient corner.
alpha2 : (num) Alpha of top-right gradient corner.
color3 : (num) Color of bottom-right gradient corner.
alpha3 : (num) Alpha of bottom-right gradient corner.
color4 : (num) Color of bottom-left gradient corner.
alpha4 : (num) Alpha of bottom-left gradient corner.

Pixel : setColor 2016.06+


Sets the color of the Pixel
Pixel:setColor([color] [, alpha])
color : (num) new color
alpha : (num) New alpha value

Pixel : setColor 2011.6+


Sets two-colour gradient fill with optional rotation to Pixel.
Pixel:setColor(color1, alpha1, color2, alpha2 [, angle])

Gideros API Reference v2017.12 Page 63


color1 : (num) First color of the gradient.
alpha1 : (num) First alpha of the gradient.
color2 : (num) Second color of the gradient.
alpha2 : (num) Second alpha of the gradient.
angle : (num) Sets rotation of the gradient in degrees. Default value is 270: top-bottom gradient.

Pixel : setColor 2011.6+


Sets 4-colour gradient fill to Pixel.
Pixel:setColor(color1, alpha1, color2, alpha2, color3, alpha3, color4, alpha4)
color1 : (num) Color of top-left gradient corner.
alpha1 : (num) Alpha of top-left gradient corner.
color2 : (num) Color of top-right gradient corner.
alpha2 : (num) Alpha of top-right gradient corner.
color3 : (num) Color of bottom-right gradient corner.
alpha3 : (num) Alpha of bottom-right gradient corner.
color4 : (num) Color of bottom-left gradient corner.
alpha4 : (num) Alpha of bottom-left gradient corner.

Pixel : setDimensions 2016.06+


Sets both width and height of the Pixel.
Pixel:setDimensions(w, h)
w : (num) The new width
h : (num) The new height

Pixel : setHeight 2016.06+


Sets the height of the pixel sprite.
Pixel:setHeight(h)
h : (num) The new height

Pixel : setTexture BETA


Associate a texture to this pixel
Pixel:setTexture(texture [, slot] [, matrix])
texture : (TextureBase) The texture to associate to this pixel, or nil to deassociate.
slot : (num) The texture slot that the texture should be associated to. Leave empty or set to 0 for main texture,
or if you don't use a specific shader.
matrix : (Matrix) an optional transform for the texture

Pixel : setTextureMatrix BETA


Sets the matrix of the Pixel's texture
Pixel:setTextureMatrix(matrix)
matrix : (Matrix) The matrix.

Pixel : setTexturePosition 2011.6+

Gideros API Reference v2017.12 Page 64


Sets the texture's position
Pixel:setTexturePosition(x, y)
x : (num) x-coordinate of texture
y : (any) y-coordinate of texture

Pixel : setTextureScale BETA


Sets the texture's scale for the Pixel
Pixel:setTextureScale(sx, sy)
sx : (num) Texture's x-scale
sy : (num) Texture's y-scale

Pixel : setWidth 2016.06+


Sets the width of the pixel sprite.
Pixel:setWidth(w)
w : (num) The new width.

Gideros API Reference v2017.12 Page 65


RenderTarget Inherits: TextureBase 2013.06+
RenderTarget is a texture on which provided Sprite hierarchy can be rendered.It can be used in any case in
which Texture can be used.

Using as texture and updating RenderTarget


--original bitmap
local source=Bitmap.new(Texture.new("crate.png", true))

--render target
local rt=RenderTarget.new(source:getWidth(), source:getHeight())

--bitmap with rendertarget as texture


local bmp=Bitmap.new(rt)
bmp:setPosition(200, 0)
stage:addChild(bmp)

--updating source updated Bitmap


local frame=0
stage:addEventListener(Event.ENTER_FRAME, function(event)
local r=math.sin(frame*0.03)*0.3+0.7
local g=math.sin(frame*0.04)*0.3+0.7
local b=math.sin(frame*0.05)*0.3+0.7
source:setColorTransform(r, g, b, 1)
frame=frame+1
rt:draw(source)
end)

RenderTarget . new 2013.06+


Creates new RenderTarget object
RenderTarget.new(width, height, filtering)
width : (num) width of rendered texture
height : (num) height of rendered texture
filtering : (boolean, default = false) Whether or not the texture is filtered.

RenderTarget : clear 2013.06+


Clears rendered texture with provided color and opacity
RenderTarget:clear(color, alpha [, x] [, y] [, width] [, height])
color : (num) color using which to clear the texture
alpha : (num) transparency using which to clear the texture
x : (num) relative x coordinate
y : (num) relative y coordinate
width : (num) width of the area to clear starting from x coordinate
height : (num) height of the area to clear starting from y coordinate

RenderTarget : draw 2013.06+


Renders provided object or object hierarchy as a texture.
RenderTarget:draw(sprite [, x] [, y])

Gideros API Reference v2017.12 Page 66


sprite : (Sprite) any sprite inherited object or object hierarchy to render (this object doesn't need to be added
to the stage hierarchy)
x : (number, default = 0) The x start position of the texture
y : (number, default = 0) The y start position of the texture

RenderTarget : getPixel 2016.06+


Returns single pixels color and alpha channel
num, num = RenderTarget:getPixel(x, y)

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

RenderTarget : getPixels 2016.06+


Returns buffer containing color and alpha data from provided rectangle
buffer = RenderTarget:getPixels(x, y, w, h)

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

RenderTarget : save 2016.08+


save contents of RenderTarget as image
RenderTarget:save(filename [, x] [, y] [, width] [, height])
filename : (str) filename and path to store file, like |D|image.png
x : (num) x coordinate from where to start image
y : (num) y coordinate from where to start image
width : (num) width of the image to save
height : (num) height of the image to save

Gideros API Reference v2017.12 Page 67


Screen Inherits: Sprite 2017.8+
Screen class allows to access secondary displays or windows.

Screen . new 2017.8+


Open a screen of the specified platform dependant type id. For desktop exports, set id to 0.
Screen.new(id)
id : (num) The kind of screen to open, platform dependant

Screen : clear 2017.8+


Sets this screen's background to the provided color and opacity
Screen:clear(color, alpha)
color : (num) background color
alpha : (num) background transparency

Screen : getId 2017.8+


Return the id this screens was created with.
num = Screen:getId()
num : The Screen's id

Screen : getMaxSize 2017.8+


Returns the maximum size this screen can have, typically the display size for a windowed system.
num, num = Screen:getMaxSize()
num : The Screen's maximum width
num : The Screen's maximum height

Screen : getPosition 2017.8+


Return the position of the screen on the display, for windowed systems
num, num = Screen:getPosition()
num : The Screen's x coordinate
num : The Screen's y coordinate

Screen : getSize 2017.8+


Return the width and height of the screen
num, num = Screen:getSize()
num : The Screen's width
num : The Screen's height

Screen : getState 2017.8+


Return the state of the screen. The returned number is the or-sum of the following possible values: *
Screen.STATE_MINIMIZED: Screen/Window is minimized. * Screen.STATE_MAXIMIZED:
Screen/Window is maximized. * Screen.STATE_FULLSCREEN: Screen/Window is fullscreen. *

Gideros API Reference v2017.12 Page 68


Screen.STATE_ACTIVE: Screen/Window is active/focused. * Screen.STATE_HIDDEN: Screen/Window is
not displayed. * Screen.STATE_CLOSED: Screen/Window is closed.
num = Screen:getState()
num : The Screen's state

Screen : setContent 2017.8+


Specify which sprite should be displayed by this Screen
Screen:setContent(content)
content : (sprite) The sprite hierarchy to be displayed by this Screen

Screen : setPosition 2017.8+


Attempts to position this screen or window, if allowed by the platform.
Screen:setPosition(x, y)
x : (num) The new x coordinate
y : (num) The new y coordinate

Screen : setSize 2017.8+


Attempts to fix the size of this screen or window, if allowed by the platform.
Screen:setSize(w, h)
w : (num) The new width
h : (num) The new height

Screen : setState 2017.8+


Attempts to configure this screen or window, if allowed by the platform.
Screen:setState(state)
state : (num) The required state of this screen

Gideros API Reference v2017.12 Page 69


Shader Inherits: Object 2015.06.30+
Gideros internally uses five distinct shaders:- the Basic shader handle shapes with a constant color- the
Color shader handle shapes with per-vertex colors (mostly used by Mesh sprite)- the Texture shader
handle textured shapes (Bitmaps)- the TextureColor shader handle textured and per-vertex colored
shapes- and the Particle shader deals with Box2D particle systemsThe new shader API allows to replace
the default shader used by Gideros with a custom one, on a sprite per sprite basis. As with most of Gideros
APIs this one is straight-forward: create a Shader object and assign it to one or several sprites.That said,
since Gideros will use your shader as if it was the standard one, you will have to make sure that your custom
shader is compatible with the standard one, which essentially means that it takes the same input parameters.

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}, });

shader:setConstant("fRad",Shader.CINT,1,0) --Initial blur level


shader:setConstant("fTexelSize",Shader.CFLOAT4,1,{1/texw,1/texh,0,0}) --Initial texel size

sprite:setShader(shader)

Shader . new 2015.06.30+


Create new shader instance.The Shader.new() constructor takes five arguments:- The path and name for
the vertex shader without its extension. Gideros will search the assets for a file with the supplied name,
automatically adding the extension relevant for the target platform: .glsl for OpenGL, .cso or .hlsl for DirectX.-
The path and name for the fragment shader without its extension. Same remark as above applies too.- A set
of numerical flags or 0 if none. See description below.- An array of uniforms/constants descriptors- An array
of attributes descriptors
Shader.new(vertex shader, fragment shader, flags, uniform descriptor, attribute descriptor)
vertex shader : (str) The path and name for the vertex shader without its extension
fragment shader : (str) The path and name for the fragment shader without its extension
flags : (num) A set of numerical flags or 0 if none
uniform descriptor : (table) An array of uniforms/constants descriptors
attribute descriptor : (table) An array of attributes descriptors

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},

Gideros API Reference v2017.12 Page 70


{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}, });

shader:setConstant("fRad",Shader.CINT,1,0) --Initial blur level


shader:setConstant("fTexelSize",Shader.CFLOAT4,1,{1/texw,1/texh,0,0}) --Initial texel size

sprite:setShader(shader)

Shader : getEngineVersion 2015.06.30+


Returns the version of the shader engine
str = Shader:getEngineVersion()
str : shader engine version

Shader : getShaderLanguage 2016.08+


Get shader language, returns string with values as: glsl or hlsl
Shader:getShaderLanguage()

Shader : setConstant 2015.06.30+


To change the value of a uniform from lua
Shader:setConstant(uniform name, data type, mult, data)
uniform name : (str) The uniform name to change
data type : (int) The type if data to set (one of the Shader.Cxxx constants)
mult : (num) number of elements of the given type to set
data : (varies) And the actual data to set, either as a table or as multiple arguments

Gideros API Reference v2017.12 Page 71


Shape Inherits: Sprite 2011.6+
The `Shape` class is used create and display vector graphics.

Drawing red square


local shape=Shape.new()
shape:setFillStyle(Shape.SOLID, 0xff0000, 1)
shape:beginPath()
shape:moveTo(0,0)
shape:lineTo(100, 0)
shape:lineTo(100, 100)
shape:lineTo(0, 100)
shape:lineTo(0, 0)
shape:endPath()
shape:setPosition(0, 150)
stage:addChild(shape)

Shape . new 2011.6+


Creates a new `Shape` object.
Shape.new()

Shape : beginPath 2011.6+


Resets the current path.
Shape:beginPath(winding)
winding : (string, default = Shape.EVEN_ODD) Specifies the winding rule. It can be either Shape.EVEN_ODD or
Shape.NON_ZERO.

Shape : clear 2011.6+


Clears the graphics that were drawn to this `Shape` object, and resets fill and line style settings.
Shape:clear()

Shape : closePath 2011.6+


Marks the current subpath as closed, and starts a new subpath with a point the same as the start and end of
the newly closed subpath.
Shape:closePath()

Shape : endPath 2011.6+


Ends the current path and draws the geometry by using the specified line and fill styles.
Shape:endPath()

Shape : lineTo 2011.6+


Adds the given point to the current subpath, connected to the previous one by a straight line.
Shape:lineTo(x, y)

Gideros API Reference v2017.12 Page 72


x : (num) x coordinate of the point.
y : (num) y coordinate of the point.

Shape : moveTo 2011.6+


Creates a new subpath with the given point.
Shape:moveTo(x, y)
x : (num) x coordinate of the point.
y : (num) y coordinate of the point.

Shape : setFillStyle 2011.6+


Sets the fill style that `Shape` object uses for subsequent drawings. The fill style remains in effect until you
call `setFillStyle()` function with differentparameters.`type` parameter can be one of the following
values:<ul><li>**Shape.NONE:** Clears the fill style.</li><li>**Shape.SOLID:** Sets the fill style as a solid
color. In this mode, the parameters are color (in hexedecial value) and an optional alpha
value.</li><li>**Shape.TEXTURE:** Sets the fill style as a textured. In this mode, the parameters are texture
and an optional transformation matrix.</li></ul>See the following example for more detailed usage of this
function.
Shape:setFillStyle(type, ...)
type : (str) The type of the fill. Can be one of the Shape.NONE, Shape.SOLID or Shape.TEXTURE.
... : (any) Parameters of the fill style.

Example:
setFillStyle(Shape.NONE) -- clears the fill style

setFillStyle(Shape.SOLID, 0xff0000) -- sets the fill style as solid red color

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'

local matrix=Matrix.new(0.5, 0, 0, 0.5, 0, 0)


setFillStyle(Shape.TEXTURE, texture, matrix) -- sets the fill style as texture with 'image.png'
with a transformation matrix
</code></pre>
<!--
<pre><code>
setFillStyle(Shape.LINEAR_GRADIENT, {}, {}, {}, (optional) matrix) -- not supported yet
setFillStyle(Shape.RADIAL_GRADIENT, {}, {}, {}, (optional) matrix) -- not supported yet
</code></pre>
-->

Shape : setLineStyle 2011.6+


Sets the line style that `Shape` object uses for subsequent drawings. The line style remains in effect until you
call `setLineStyle()` function with differentparameters.
Shape:setLineStyle(width, color, alpha)

Gideros API Reference v2017.12 Page 73


width : (num) The width of the line. If this parameter is 0, line is not drawn.
color : (number, default = 0x000000) A hexadecimal color value of the line. For example, red is 0xFF0000, blue
is 0x0000FF, and so on.
alpha : (number, default = 1) The alpha value of the color of the line.

Gideros API Reference v2017.12 Page 74


Sound Inherits: Object 2011.6+
The `Sound` class lets you load and play WAV, MP3, MOD, XM, S3M and IT sound files.Control of the
playing sound is performed through the `SoundChannel`object.

Example:
local sound=Sound.new('music.mp3')

local channel=sound:play()

-- after some time --


channel:stop()

Sound . new 2011.6+


Creates a new `Sound` object.
Sound.new(filename)
filename : (str) The name of the sound file to be loaded.

Sound . setListenerPosition BETA


Sets the position of the listener in a 3D environment
Sound.setListenerPosition(x, y [, z] [, vx] [, vy] [, vz] [, dx] [, dy] [, dz] [, ux] [, uy] [, uz])
x : (num) X coordinate of the listener
y : (num) Y coordinate of the listener
z : (num) z coordinate of the listener
vx : (num) X component of listener's velocity
vy : (num) Y component of listener's velocity
vz : (num) Z component of listener's velocity
dx : (num) X component of the direction the listener is facing
dy : (num) Y component of the direction the listener is facing
dz : (num) Z component of the direction the listener is facing
ux : (num) X component of up direction relative to the listener
uy : (num) Y component of up direction relative to the listener
uz : (num) Z component of up direction relative to the listener

Sound : getLength 2011.6+


Returns the duration of the sound in miliseconds.
num = Sound:getLength()
num : The duration of the sound in miliseconds.

Sound : play 2011.6+


Creates a new `SoundChannel` object to play the sound. By using the retured `SoundChannel` object,you
can stop the sound and monitor the position.
SoundChannel = Sound:play(startTime, looping, paused)

Parameters:
startTime : (number, default = 0) The initial position in milliseconds at which playback should start.
looping : (boolean, default = false)

Gideros API Reference v2017.12 Page 75


paused : (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.

Gideros API Reference v2017.12 Page 76


SoundChannel Inherits: Object 2011.6+
The `SoundChannel` class is used to control and monitor a playing sound.<h3>SoundChannel
Events</h3><ul><li>`Event.COMPLETE = "complete"` When the sound channel has finished playing,
`Event.COMPLETE` event is dispatched.</li></ul>

SoundChannel : getPitch 2012.09.3+


Returns the current pitch of the sound channel. (Original pitch is 1)
any, any = SoundChannel:getPitch()
any : The current pitch of the sound channel.
any : The current pitch of the sound channel.

SoundChannel : getPosition 2011.6+


If the sound is playing, `getPosition` returns the position of the current playback, measured in miliseconds
from the start of the sound.If the sound is not playing (paused or stopped), `getPosition` returns the last point
that was played.
num = SoundChannel:getPosition()
num : The position of the sound in miliseconds.

SoundChannel : getVolume 2011.6+


Returns the current volume of the sound channel.
num = SoundChannel:getVolume()
num : The current volume of the sound channel.

SoundChannel : isLooping 2011.6+


Returns the looping state of the channel.
bool = SoundChannel:isLooping()
bool : `true` if the channel is looping, `false` otherwise.

SoundChannel : isPaused 2011.6+


Returns the paused state of the channel.
bool = SoundChannel:isPaused()
bool : `true` if the channel is paused, `false` otherwise.

SoundChannel : isPlaying 2011.6+


Returns the playing state for the sound channel.
any, any = SoundChannel:isPlaying()
any : `true` if the channel is currently playing a sound, `false` otherwise.
any : `true` if the channel is currently playing a sound, `false` otherwise.

SoundChannel : setLooping 2011.6+


Sets the looping state of the channel.

Gideros API Reference v2017.12 Page 77


SoundChannel:setLooping(looping)
looping : (bool) looping state to set

SoundChannel : setPaused 2011.6+


Sets the paused state of the channel.
SoundChannel:setPaused(paused)
paused : (bool) paused state to set

SoundChannel : setPitch 2012.09.3+


Sets the pitch relative to the pitch of the original sound channel. Default pitch is 1. Setting pitch as 0.5 will
make the pitch lowerSetting pitch as 1.5 will make the pitch higherYou cannot set the pitch of a background
music (mp3).
SoundChannel:setPitch(pitch)
pitch : (num) pitch relative to original (1 < - higher pitch, 1 > 0 lower pitch)

SoundChannel : setPosition 2011.6+


Sets the current playback position in miliseconds.
SoundChannel:setPosition(position)
position : (num) position of the channel to set in miliseconds

SoundChannel : setVolume 2011.6+


Sets the volume of the sound channel.
SoundChannel:setVolume(volume)
volume : (num) The new volume of the sound channel. Valid range of this parameter is between 0.0 and 1.0,
where 1.0 is the maximum volume value.

SoundChannel : setWorldPosition BETA


Sets the position of this sound in a 3D world
SoundChannel:setWorldPosition(x, y [, z] [, vx] [, vy] [, vz])
x : (num) X coordinate of this sound
y : (num) Y coordinate of this sound
z : (num) Z coordinate of this sound
vx : (num) X component of this sound's velocity
vy : (num) Y component of this sound's velocity
vz : (num) Z component of this sound's velocity

SoundChannel : stop 2011.6+


Stops the sound playing in the channel.
SoundChannel:stop()

Gideros API Reference v2017.12 Page 78


Sprite Inherits: EventDispatcher 2011.6+
The `Sprite` class is the base class for all objects that can be placed on the scene tree. It is the basic scene
tree building block.A sprite can contain child sprites which makes the scene tree hierarchy.Transformations
such as translation, rotation, scaling and color transforms propogates its effect to all of its children.The
drawing order is defined by the order of children. First child is drawn first and last child is drawn last. It is
possible to change the drawing order by modifying the order of child list.A `Sprite` instance can exists
without attaching the scene tree.An unattached sprite can receive `Event.ENTER_FRAME` event but it will
only receive mouse and touch events when it is attached to the scene tree.

Sprite . new 2011.6+


Creates a new Sprite object
Sprite.new()

Sprite : addChild 2011.6+


Adds a sprite as a child to this sprite. The child isadded as a last child of this `Sprite` instance.Sprites can
have only one parent. Therefore if you add a childobject that already has a different sprite as a parent,the
sprite is removed from the child list of the other spriteand then added to this sprite.
Sprite:addChild(child)
child : (Sprite) The child sprite to add.

Sprite : addChildAt 2011.6+


Adds a sprite as a child to this sprite. The child isadded at the index position specified. Indices start from
1.Sprites can have only one parent. Therefore if you add a childobject that already has a different sprite as
a parent,the sprite is removed from the child list of the other spriteand then added to this sprite.
Sprite:addChildAt(child, index)
child : (Sprite) The child sprite to add.
index : (num) The index position to which the child is added.

Sprite : clearBlendMode 2011.6+


Clears the blending mode.
Sprite:clearBlendMode()

Sprite : contains 2011.6+


Determines whether the specified sprite is contained in the subtree ofthis `Sprite` instance.
bool = Sprite:contains(child)

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

Sprite : get 2011.6+


Returns the specified property of this sprite instance by its name. These names are

Gideros API Reference v2017.12 Page 79


supported:<ul><li>`"x"`</li><li>`"y"`</li><li>`"z"`</li><li>`"rotation"`</li><li>`"rotationX"`</li><li>`"rotationY
"`</li><li>`"scaleX"`</li><li>`"scaleY"`</li><li>`"scaleZ"`</li><li>`"alpha"`</li><li>`"redMultiplier"`</li><li>`"g
reenMultiplier"`</li><li>`"blueMultiplier"`</li><li>`"alphaMultiplier"`</li><li>`"anchorX"`</li><li>`"anchorY"`</li
><li>`"anchorZ"`</li></ul>
num = Sprite:get(param)

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

-- the following two lines do the same thing


y=sprite:getY()
y=sprite:get('y')

-- the following two lines do the same thing


rotation=sprite:getRotation()
rotation=sprite:get('rotation')

-- the following two lines do the same thing


scaleX=sprite:getScaleX()
scaleX=sprite:get('scaleX')

-- the following two lines do the same thing


scaleY=sprite:getScaleY()
scaleY=sprite:get('scaleY')

Sprite : getAlpha 2011.6+


Returns the alpha transparency of this sprite. 0 means fully transparent and 1 means fully opaque.
num = Sprite:getAlpha()
num : The alpha of the sprite (value between 0-1)

Sprite : getAnchorPosition 2015.03.22+


Returns x,y,z anchor position of the `Sprite` in its relative coordinates
num, num, num = Sprite:getAnchorPosition()
num : anchor x position
num : anchor y position
num : anchor z position

Sprite : getBounds 2011.6+


Returns a rectangle (as x, y, width and height) that encloses the sprite as it appears in another sprite's
coordinate system.
num, num, num, num = Sprite:getBounds(targetSprite)

Gideros API Reference v2017.12 Page 80


Parameter:
targetSprite : (Sprite) the sprite that defines the other coordinate system to transform

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

Sprite : getChildAt 2011.6+


Returns the child `Sprite` instance that exists at the specified index. First child is at index 1.
Sprite = Sprite:getChildAt(index)

Parameter:
index : (num) The index position of the child object.

Result:
Sprite : The child sprite at the specified index position.

Sprite : getChildIndex 2011.6+


Returns the index of the specified child sprite.
num = Sprite:getChildIndex(child)

Parameter:
child : (Sprite) The child sprite to identify.

Result:
num : The index of the specified child sprite.

Sprite : getClip BETA


Returns the coordinates of the Sprite clip range if set with setClip
num, num, num, num = Sprite:getClip()
num : x-coordinate of clip origin
num : y-coordinate of clip origin
num : width of clip region
num : Height of clip region

Sprite : getColorTransform 2011.6+


Returns the red, green, blue and alpha channel multipliers.
num, num, num, num = Sprite:getColorTransform()
num : redMultiplier
num : greenMultiplier
num : blueMultiplier
num : alphaMultiplier

Gideros API Reference v2017.12 Page 81


Sprite : getHeight 2011.6+
Returns the height of the sprite, in pixels. The height is calculated based on thebounds of the content of the
sprite.If "true" is passed to this method, the original height is returned without accounting for
transformations.
num = Sprite:getHeight([withoutTransform])

Parameter:
withoutTransform : (bool) If true, return the height without transformation, else return the transformed height

Result:
num : Height of the sprite.

Sprite : getMatrix 2011.6+


Returns the transformation matrix of the sprite. Each invocation of this function returns a new `Matrix` object.
Matrix = Sprite:getMatrix()
Matrix : The transformation matrix of the sprite

Sprite : getNumChildren 2011.6+


Returns the number of children of this sprite.
num = Sprite:getNumChildren()
num : The number of children of this 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

Sprite : getParent 2011.6+


Returns the `Sprite` object that contains this `Sprite` object.
Sprite = Sprite:getParent()
Sprite : The parent sprite.

Sprite : getPosition 2011.6+


Returns the x, y and z coordinates of the sprite.
num, num, num = Sprite:getPosition()
num : The x coordinates of the sprite

Gideros API Reference v2017.12 Page 82


num : The y coordinates of the sprite
num : The z coordinates of the sprite

Sprite : getRotation 2011.6+


Returns the rotation of the sprite in degrees.
num = Sprite:getRotation()
num : Rotation of the Sprite in degrees

Sprite : getRotationX 2015.04.04+


Returns the rotation of the sprite around x axis in degrees.
num = Sprite:getRotationX()
num : Rotation of the Sprite on x in degrees

Sprite : getRotationY 2015.04.04+


Returns the rotation of the sprite around Y axis in degrees.
num = Sprite:getRotationY()
num : Rotation of the Sprite on y in degrees

Sprite : getScale 2011.6+


Returns the horizontal, vertical and z axis scales of the sprite.
num, num, num = Sprite:getScale()
num : The horizontal scale of the sprite
num : The vertical scale of the sprite
num : The depth scale of the sprite

Sprite : getScaleX 2011.6+


Returns the horizontal scale of the sprite.
num = Sprite:getScaleX()
num : The horizontal scale of the sprite.

Sprite : getScaleY 2011.6+


Returns the vertical scale of the sprite.
num = Sprite:getScaleY()
num : The vertical scale of the object.

Sprite : getScaleZ 2015.04.04+


Returns the scale on z axis of the sprite.
num = Sprite:getScaleZ()
num : z axis scale

Sprite : getSkew BETA

Gideros API Reference v2017.12 Page 83


Returns the x and y skew parameters of the Sprite
num, num = Sprite:getSkew()
num : The x-skew of the Sprite
num : The y-skew of the Sprite

Sprite : getSkewX BETA


Returns the sprite's X-skew (ie shear)
num = Sprite:getSkewX()
num : The sprite's X-skew

Sprite : getSkewY BETA


Returns the y-skew of the Sprite
num = Sprite:getSkewY()
num : The y-skew of the Sprite

Sprite : getWidth 2011.6+


Returns the width of the sprite, in pixels. The width is calculated based on thebounds of the content of the
sprite.If the parameter "true" is passed, the original width is returned without transformations.
any, any = Sprite:getWidth([withoutTransform])

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.

Sprite : getX 2011.6+


Returns the x coordinate of the sprite.
num = Sprite:getX()
num : The x coordinate of the sprite

Sprite : getY 2011.6+


Returns the y coordinate of the sprite.
num, any = Sprite:getY()
num : The y coordinate of the sprite
any : The y coordinate of the sprite

Sprite : getZ 2015.04.04+


Returns the z coordinate of the sprite.
num = Sprite:getZ()
num : z position

Gideros API Reference v2017.12 Page 84


Sprite : globalToLocal 2011.6+
Converts the x,y coordinates from the global to the sprite's (local) coordinates.
num, num = Sprite:globalToLocal(x, y)

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.

Sprite : hitTestPoint 2011.6+


Checks whether the given coordinates (in global coordinate system) is in bounds of the sprite.
bool = Sprite:hitTestPoint(x, y [, shapeFlag])

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.

Sprite : isVisible 2011.6+


Returns whether or not the sprite is visible. Child sprites that are not visible are also takeninto consideration
while calculating bounds.
bool = Sprite:isVisible()
bool : A value of `true` if sprite is visible; `false` otherwise.

Sprite : localToGlobal 2011.6+


Converts the x,y coordinates from the sprite's (local) coordinates to the global coordinates.
num, num = Sprite:localToGlobal(x, y)

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.

Sprite : removeChild 2011.6+


Removes the specified child `Sprite` instance from the child list of this `Sprite` instance.
Sprite:removeChild(child)
child : (Sprite) The child sprite to remove.

Sprite : removeChildAt 2011.6+

Gideros API Reference v2017.12 Page 85


Removes the child `Sprite` instance at the specifed index. Index of the first child is 1and index of the last
child can be get from `Sprite:getNumChildren` function.
Sprite:removeChildAt(index)
index : (num) The child index of the sprite to remove.

Sprite : removeFromParent 2011.6+


If the sprite has a parent, removes the sprite from the child list of its parent sprite. This function is equilavent
to:<pre><code>function Sprite:removeFromParent()local parent = self:getParent()if parent ~= nil
thenparent:removeChild(self)endend</code></pre>
Sprite:removeFromParent()

Sprite : set 2011.6+


Sets the specified property of this sprite instance by its name. These names are
supported:<ul><li>`"x"`</li><li>`"y"`</li><li>`"z"`</li><li>`"rotation"`</li><li>`"rotationX"`</li><li>`"rotationY
"`</li><li>`"scaleX"`</li><li>`"scaleY"`</li><li>`"scaleZ"`</li><li>`"alpha"`</li><li>`"redMultiplier"`</li><li>`"g
reenMultiplier"`</li><li>`"blueMultiplier"`</li><li>`"alphaMultiplier"`</li><li>`"anchorX"`</li><li>`"anchorY"`</li
><li>`"anchorZ"`</li></ul>
Sprite:set(param, value)
param : (str) The name of the parameter
value : (num) The new value of the specified parameter

Example:
-- the following two lines do the same thing
sprite:setX(10)
sprite:set('x', 10)

-- the following two lines do the same thing


sprite:setY(10)
sprite:set('y', 10)

-- the following two lines do the same thing


sprite:setRotation(10)
sprite:set('rotation', 10)

-- the following two lines do the same thing


sprite:setScaleX(0.5)
sprite:set('scaleX', 0.5)

-- the following two lines do the same thing


sprite:setScaleY(0.5)
sprite:set('scaleY', 0.5)

-- the following two lines do the same thing


sprite:setScale(0.5)
sprite:set('scale', 0.5)

Sprite : setAlpha 2011.6+


Sets the alpha transparency of this sprite. 0 means fully transparent and 1 means fully opaque.

Gideros API Reference v2017.12 Page 86


Sprite:setAlpha(alpha)
alpha : (num) The new alpha transparency of the sprite

Sprite : setAnchorPosition 2015.03.22+


Sets x, y, z anchor position of `Sprite` in it's relative coordinates.Meaning Sprite with dimensions 100x100
and anchor position of 50x50 would rotate around its center
Sprite:setAnchorPosition(anchorX, anchorY [, anchorZ])
anchorX : (num) Anchor position in Sprite's internal coordinates
anchorY : (num) Anchor position in Sprite's internal coordinates
anchorZ : (num) Anchor position in Sprite's internal coordinates

Sprite : setBlendMode 2011.6+


Sets the blend mode of the sprite. This method can be called with 1 or 2 parameters. If one parameter is
passed it must be one of the following blending modes:<ul><li>Sprite.ALPHA =
"alpha"</li><li>Sprite.NO_ALPHA = "noAlpha"</li><li>Sprite.ADD = "add"</li><li>Sprite.MULTIPLY =
"multiply"</li><li>Sprite.SCREEN = "screen"</li></ul>If a `Sprite` object doesn't set any blending mode, it
takes the blending mode from its parent sprite.<ul><li>*Note:** The following two lines are completely
same:</li></ul><pre><code>sprite:setBlendMode("add")sprite:setBlendMode(Sprite.ADD)</code></pre>
It's a matter of taste which one to choose.If two parameters are passed to this method, then a source and
destination blend can be set (in that order) and each take the values:<ul><li>Sprite.ZERO =
"zero"</li><li>Sprite.ONE = "one"</li><li>Sprite.SRC_COLOR =
"srcColor"</li><li>Sprite.ONE_MINUS_SRC_COLOR = "oneMinusSrcColor"</li><li>Sprite.DST_COLOR =
"dstColor"</li><li>Sprite.ONE_MINUS_DST_COLOR = "oneMinusDstColor"</li><li>Sprite.SRC_ALPHA =
"srcAlpha"</li><li>Sprite.ONE_MINUS_SRC_ALPHA = "oneMinusSrcAlpha"</li><li>Sprite.DST_ALPHA =
"dstAlpha"</li><li>Sprite.ONE_MINUS_DST_ALPHA =
"oneMinusDstAlpha"</li><li>Sprite.SRC_ALPHA_SATURATE = "srcAlphaSaturate"</li></ul>
Sprite:setBlendMode(blendMode or src [, dst])
blendMode or src : (str) If one parameter is used, this is the blend mode. If two parameters are used this is
the source blend specification.
dst : (str) Destination blend mode

Sprite : setClip 2015.04.04+


Clip Sprite contents from provided x, y position to provided width and heightSetting width or height to -1 will
disable it
Sprite:setClip(x, y, width, height)
x : (num) x position from where to clip
y : (num) y position from where to clip
width : (num) width of how much to display before clipping
height : (num) width of how much to display before clipping

Sprite : setColorTransform 2011.6+


Sets the red, green, blue and alpha channel multipliers (values between 0 and 1). This function lets you
adjust the color multipliers of a display object.This adjustment also applies to the children of this sprite
instance.
Sprite:setColorTransform(redMultiplier, greenMultiplier, blueMultiplier, alphaMultiplier)
redMultiplier : (number, default = 1) The red multiplier of this sprite (values between 0 and 1)

Gideros API Reference v2017.12 Page 87


greenMultiplier : (number, default = 1) The green multiplier of this sprite(values between 0 and 1)
blueMultiplier : (number, default = 1) The blue multiplier of this sprite(values between 0 and 1)
alphaMultiplier : (number, default = 1) The alpha multiplier of this sprite(values between 0 and 1)

Sprite : setMatrix 2011.6+


Sets the transformation matrix of the sprite.
Sprite:setMatrix(matrix)
matrix : (Matrix)

Sprite : setPosition 2011.6+


Sets the x, y and z coordinates of the sprite.
Sprite:setPosition(x, y [, z])
x : (num) The new x coordinate of the sprite
y : (num) The new y coordinate of the sprite
z : (num) The new z coordinate of the sprite

Sprite : setRotation 2011.6+


Sets the rotation of the sprite in degrees.
Sprite:setRotation(rotation)
rotation : (num) rotation of the sprite

Sprite : setRotationX 2015.04.04+


Sets the rotation of the sprite in degrees around x axis.
Sprite:setRotationX()

Sprite : setRotationY 2015.04.04+


Sets the rotation of the sprite in degrees around y axis.
Sprite:setRotationY()

Sprite : setScale 2011.6+


Sets the horizontal, vertical and z axis scales of the sprite.
Sprite:setScale(scaleX, scaleY, scaleZ)
scaleX : (num) of the object
scaleY : (number, default = scaleX) of the object
scaleZ : (number, default = scaleX) of the object

Sprite : setScaleX 2011.6+


Sets the horizontal scale of the sprite.
Sprite:setScaleX(scaleX)
scaleX : (num) horizontal scale of the sprite

Gideros API Reference v2017.12 Page 88


Sprite : setScaleY 2011.6+
Sets the vertical scale of the sprite.
Sprite:setScaleY(scaleY)
scaleY : (num) of the object

Sprite : setScaleZ 2015.04.04+


Set scale on z axis
Sprite:setScaleZ(scale)
scale : (num) scale on z axis

Sprite : setShader 2015.06.30+


Set shader for this sprite. If nil is provided, sets default shader for current object
Sprite:setShader(shader)
shader : (Shader) shader to use for this object

Sprite : setShaderConstant 2017.4+


To change the value of a uniform from lua
Sprite:setShaderConstant(uniform name, data type, mult, data)
uniform name : (str) The uniform name to change
data type : (int) The type if data to set (one of the Shader.Cxxx constants)
mult : (num) number of elements of the given type to set
data : (varies) And the actual data to set, either as a table or as multiple arguments

Sprite : setSkew BETA


Set the skew (ie shear) of the Sprite
Sprite:setSkew(kx, ky)
kx : (num) The x-skew of the Sprite
ky : (num) The y-skew of the Sprite

Sprite : setSkewX BETA


Skew (aka "shear") transformation effect
Sprite:setSkewX(kx)
kx : (num) Amount of skew in range -90... 90 degrees

Sprite : setSkewY BETA


Set's the Sprite's Y-skew (ie shear)
Sprite:setSkewY(ky)
ky : (num) The y-skew of the Sprite

Sprite : setStencilOperation 2017.6+


Allows to set a stencil operation to be used when drawing this sprite. The table can contain the following

Gideros API Reference v2017.12 Page 89


fields: <ul> <li><b>stencilClear</b>: (boolean) whether the stencil should be cleared beforehand.</li>
<li><b>stencilMask</b>: (integer) the mask value used in stencil operations.</li>
<li><b>stencilWriteMask</b>: (integer) the mask value used when writing to stencil.</li>
<li><b>stencilRef</b>: (integer) the reference value used in stencil operations.</li> <li><b>stencilFunc</b>:
(integer) the stencil function to use.</li> <li><b>stencilFail</b>: (integer) the stencil operation when stencil
test failed.</li> <li><b>depthFail</b>: (integer) the stencil operation when depth test failed.</li>
<li><b>depthPass</b>: (integer) the stencil operation when depth test has passed.</li> </ul> Stencil
function and operations code are defined in Sprite.STENCIL_xxx fields and correspond to the GL_xxx
relevant values in OpenGL stencil documentation.
Sprite:setStencilOperation(op)
op : (table) A table containing the stencil operation settings, or nil to disable stencil

Sprite : setVisible 2011.6+


Sets whether or not the sprite is visible. Sprites that are not visible are also takeninto consideration while
calculating bounds.
Sprite:setVisible(visible)
visible : (bool) whether or not the sprite is visible

Sprite : setX 2011.6+


Sets the x coordinate of the sprite
Sprite:setX(x)
x : (num) The new x coordinate of the sprite

Sprite : setY 2011.6+


Sets the y coordinate of the sprite.
Sprite:setY(y)
y : (num) The new y coordinate of the sprite

Sprite : setZ 2015.04.04+


Sets the z coordinate of the sprite
Sprite:setZ(z)
z : (num) position on z axis

Sprite : swapChildren 2015.04.04+


Swap two children index places
Sprite:swapChildren(child1, child2)
child1 : (Sprite) First child
child2 : (Sprite) Second child

Sprite : swapChildrenAt 2015.04.04+


Swaps two child sprites at specifed indexes. Each index must be between 1and the index number of the last
child. Can be used to sort sprites intoa specific order much faster than adding and removing sprites.
Sprite:swapChildrenAt(index1, index2)

Gideros API Reference v2017.12 Page 90


index1 : (num) The child index of the first sprite to swap.
index2 : (num) The child index of the second sprite to swap.

Gideros API Reference v2017.12 Page 91


Stage Inherits: Sprite 2011.6+
The `Stage` class represents the top of the scene tree hierarchy. The instances of `Stage` is not created
directly (there is not any `Stage.new` function) butthere is already a global variable `stage`.

Stage : setClearColorBuffer 2011.6+


If you are covering whole background with image, you can disable background color draw call for better
performance
Stage:setClearColorBuffer(state)
state : (bool) false to disable draw call, true to enable

Gideros API Reference v2017.12 Page 92


TextField Inherits: Sprite 2011.6+
The `TextField` class is used to create display objects for text display.

Example:
local font=Font.new('myfont.txt', 'myfont.png')

local textfield=TextField.new(font, 'some text')

stage:addChild(textfield)

textfield:setText('some other text') -- change the text

-- to use the default font, pass nil value for the font parameter
local textfield2=TextField.new(nil, 'some other text with default font')

TextField . new 2011.6+


Creates a new `TextField` object with the specified font and text. Gideros runtime includes adefault font. If
you specify `nil` for the font parameter while creating the `TextField` object, default font is used.
TextField.new(font, text [, sample] [, layout])
font : (FontBase) The font used for displaying this `TextField` object. If nil, default font is used.
text : (string, optional) The text to be displayed.
sample : (str) sample to determine line height
layout : (table) Layout parameters, see `TextField:setLayout`

TextField : getLayout 2017.10+


Retrieve the layout parameters of this TextField
table = TextField:getLayout()
table : Layout parameters

TextField : getLetterSpacing 2011.6+


Returns the letter-spacing property which is used to increase or decrease the space between characters in a
text.
num = TextField:getLetterSpacing()
num : The letter-spacing property of the text field.

TextField : getLineHeight 2016.08+


Get line height
num = TextField:getLineHeight()
num : line height in pixels

TextField : getSample 2016.08+


get string that was used as sample for determining line height
str = TextField:getSample()
str : string used as sample

Gideros API Reference v2017.12 Page 93


TextField : getText 2011.6+
Returns the text displayed.
str = TextField:getText()
str : The text displayed.

TextField : getTextColor 2011.6+

num = TextField:getTextColor()
num : The color of the text in a text field, in hexadecimal format.

TextField : setFont 2016.08+


set font to use
TextField:setFont(font)
font : (FontBase) font to use

TextField : setLayout 2017.10+


Change the layout parameters for this TextFieldLayout parameters can contain the following fields: - w,h:
Width/height of the area to layout the text in - flags: A or combination of `FontBase`.TLF_xxx constants
instructing how to layout the text - letterSpacing: The space to add between each letter of the text -
lineSpacing: The space to add between each line of the text - tabSpace: The size of a tab in space
characters increment, default to 4 if unspecified
TextField:setLayout(layout)
layout : (table) Layout parameters

TextField : setLetterSpacing 2011.6+


Sets the letter-spacing property which is used to increase or decrease the space between characters in a
text.
TextField:setLetterSpacing(spacing)
spacing : (num)

TextField : setSample 2016.08+


Set string that will be used as sample for determining text's line height
TextField:setSample(sample)
sample : (str) string to use as sample

TextField : setText 2011.6+


Sets the text to be displayed.
TextField:setText(text)
text : (str) The text to be displayed.

TextField : setTextColor 2011.6+

Gideros API Reference v2017.12 Page 94


Sets the color of the text in a text field in hexadecimal format.
TextField:setTextColor(color)
color : (num) color of the text in hexadecimal format.

Example:
textfield:setTextColor(0xff0000) -- red
textfield:setTextColor(0x00ff00) -- green
textfield:setTextColor(0x0000ff) -- blue

Gideros API Reference v2017.12 Page 95


TextInputDialog Inherits: AlertDialog 2012.8+
The `TextInputDialog` class is used to display native text input dialogs with one text edit field, one button (as
cancel button) and two optional buttons. When the user presses any buttons in the alert dialog, it's dismissed
and `Event.COMPLETE` event is dispatched.If text input dialog is dismissed by any other means (by
pressing back button on Android or by pressing close button on desktop), it behaves as cancel button is
pressed.

Example:
local textInputDialog=TextInputDialog.new('my title', 'my message', 'some text', 'Cancel', 'OK')

local function onComplete(event)


print(event.text, event.buttonIndex, event.buttonText)
end

textInputDialog:addEventListener(Event.COMPLETE, onComplete)
textInputDialog:show()

TextInputDialog . new 2012.8+


Creates a new `TextInputDialog` object.
TextInputDialog.new(title, message, text, cancelButton, button1, button2)
title : (str)
message : (str) Descriptive text that provides more details than the title.
text : (str) The text on the text field.
cancelButton : (str) The text of the cancel button.
button1 : (string, optional) The text of the 1st optional button.
button2 : (string, optional) The text of the 2st optional button.

TextInputDialog : getInputType 2012.8+


Returns the keyboard type associated with the text field.
str = TextInputDialog:getInputType()
str : The keyboard type associated with the text field (TextInputDialog.EMAIL, TextInputDialog.NUMBER,
TextInputDialog.PHONE, TextInputDialog.TEXT, TextInputDialog.URL)

TextInputDialog : getText 2012.8+


Returns the text on the text field.
str = TextInputDialog:getText()
str : The text on the text field.

TextInputDialog : isSecureInput 2012.8+


Returns whether the text object hides the text being entered.
bool = TextInputDialog:isSecureInput()
bool : Whether the text object hides the text being entered.

TextInputDialog : setInputType 2012.8+

Gideros API Reference v2017.12 Page 96


Sets the input (keyboard) type associated with the text field. The options
are:<ul><li>`TextInputDialog.TEXT`: Default keyboard type</li><li>`TextInputDialog.NUMBER`: Numeric
keypad</li><li>`TextInputDialog.PHONE`: Keypad designed for entering telephone
numbers</li><li>`TextInputDialog.EMAIL`: Keyboard optimized for specifying email
addresses</li><li>`TextInputDialog.URL`: Keyboard optimized for URL entry</li></ul>
TextInputDialog:setInputType(type)
type : (str) Tnput type associated with the text field.

TextInputDialog : setSecureInput 2012.8+


Sets whether the text object should hide the text being entered.
TextInputDialog:setSecureInput(secureInput)
secureInput : (bool) If 'true', the text object hides the text being entered.

TextInputDialog : setText 2012.8+


Sets the text on the text field.
TextInputDialog:setText(text)
text : (str) The text on the text field.

Gideros API Reference v2017.12 Page 97


Texture Inherits: TextureBase 2011.6+
The `Texture` class lets you work with textures in an application. The `Texture` class lets you createa new
`Texture` object to load from an image file and display in scene tree.

Texture . new 2011.6+


Creates a new Texture object.
Texture.new(filename, filtering [, options])
filename : (str) The name of the texture file to be loaded.
filtering : (boolean, default = false) Whether or not the texture is filtered.
options : (table) A table that specifies optional paramaters. Currently, "transparentColor", "wrap", "format" and
"extend" fields are supported.

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

Texture . new 2016.08+


Create a texture from pixel data.
Texture.new(pixels, width, height [, filtering] [, options])
pixels : (str) A string containing actual R,G,B,A compoents of each pixel in the new texture. Each component
is stored as a byte. You can pass nil if you don't need to initialize texture content
width : (num) width of the texture to create
height : (num) Height of the texture to create
filtering : (boolean, default to false) indicate that the texture should be filtered
options : (table) A table that specifies optional paramaters. Currently, "transparentColor", "wrap", "format" and
"extend" fields are supported.

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

Texture . new 2011.6+


Creates a new Texture object.
Texture.new(filename, filtering [, options])
filename : (str) The name of the texture file to be loaded.
filtering : (boolean, default = false) Whether or not the texture is filtered.
options : (table) A table that specifies optional paramaters. Currently, "transparentColor", "wrap", "format" and
"extend" fields are supported.

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

Gideros API Reference v2017.12 Page 98


Texture . new 2016.08+
Create a texture from pixel data.
Texture.new(pixels, width, height [, filtering] [, options])
pixels : (str) A string containing actual R,G,B,A compoents of each pixel in the new texture. Each component
is stored as a byte. You can pass nil if you don't need to initialize texture content
width : (num) width of the texture to create
height : (num) Height of the texture to create
filtering : (boolean, default to false) indicate that the texture should be filtered
options : (table) A table that specifies optional paramaters. Currently, "transparentColor", "wrap", "format" and
"extend" fields are supported.

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

Gideros API Reference v2017.12 Page 99


TextureBase Inherits: Object 2011.6+
`TextureBase` is the base class for `Texture` and `TexturePack` classes. It provides a common functionaly to
texture related classes.<ul><li>TextureBase.CLAMP = 'clamp'</li><li>TextureBase.REPEAT =
'repeat'</li></ul>

TextureBase : getHeight 2011.6+


Returns the height of the texture in pixels.
num = TextureBase:getHeight()
num : The height of the texture in pixels.

TextureBase : getWidth 2011.6+


Returns the width of the texture in pixels.
num = TextureBase:getWidth()
num : The width of the texture in pixels.

Gideros API Reference v2017.12 Page 100


TexturePack Inherits: TextureBase 2011.6+
The `TexturePack` class specifies a texture pack (or texture atlas). A texture atlas is a large image which
contains many smaller sub-images.Gideros supports dynamic creation of texture atlases and pre-packed
texture atlasses by using 'Gideros Texture Packer' tool.<h3>Dynamic Creation of Texture Packs</h3>To
create a texture pack dynamically (at run-time), create `TexturePack` object with a table of file names of
textures.<pre><code>local pack = TexturePack.new({'1.png', '2.png', '3.png',
'4.png')}</code></pre><h3>Static Creation of Texture Packs</h3>To create a pre-packed texture atlas, use
'Gideros Texture Packer' tool:![images/texture_packer.png]This tool exports two files: A `.txt` file that
specifes the positions of texture regions and a `.png` file of packed texture.Use these two files to create
texture pack:<pre><code>local pack = TexturePack.new('pack.txt', 'pack.png')</code></pre>

TexturePack . new 2011.6+


Creates a new `TexturePack` object. This function creates the texture pack at runtime.
TexturePack.new(textures, padding, filtering, options)
textures : (table) file names of textures.
padding : (num) the spacing between textures in pixels
filtering : (boolean, default = false) Whether or not the texture is filtered.
options : (table, optional) A table that specifies optional paramaters. Currently, 'transparentColor' and
'format&quot fields are supported.

TexturePack . new 2011.6+


Creates a new `TexturePack` object. This function loads the pre-packed texture atlas created by 'Gideros
Texture Packer' tool.
TexturePack.new(txtfile, imagefile, filtering, options)
txtfile : (str)
imagefile : (str)
filtering : (boolean, default = false) Whether or not the texture is filtered.
options : (table, optional) A table that specifies optional paramaters. Currently, 'transparentColor' and
'format&quot fields are supported.

TexturePack . new 2011.6+


Creates a new `TexturePack` object. This function creates the texture pack at runtime.
TexturePack.new(textures, padding, filtering, options)
textures : (table) file names of textures.
padding : (num) the spacing between textures in pixels
filtering : (boolean, default = false) Whether or not the texture is filtered.
options : (table, optional) A table that specifies optional paramaters. Currently, 'transparentColor' and
'format&quot fields are supported.

TexturePack . new 2011.6+


Creates a new `TexturePack` object. This function loads the pre-packed texture atlas created by 'Gideros
Texture Packer' tool.
TexturePack.new(txtfile, imagefile, filtering, options)
txtfile : (str)
imagefile : (str)
filtering : (boolean, default = false) Whether or not the texture is filtered.

Gideros API Reference v2017.12 Page 101


options : (table, optional) A table that specifies optional paramaters. Currently, 'transparentColor' and
'format&quot fields are supported.

TexturePack : getTextureRegion 2011.6+


Returns the texture region of texture pack.
TextureRegion = TexturePack:getTextureRegion(texturename)

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

Gideros API Reference v2017.12 Page 102


TextureRegion Inherits: Object 2011.6+
The `TextureRegion` class specifies a texture and a rectangular region in it. It is used to define independent
texture regionswithin a texture atlas which is a large image, which contains many smaller sub-images.

Example:
local texture=Texture.new('atlas.png')

-- define 4 equal regions of size 100x100 from 'atlas.png'


local region1=TextureRegion.new(texture, 0, 0, 100, 100)
local region2=TextureRegion.new(texture, 100, 0, 100, 100)
local region3=TextureRegion.new(texture, 100, 100, 100, 100)
local region4=TextureRegion.new(texture, 0, 100, 100, 100)

-- add these regions to scene tree


local bitmap1=Bitmap.new(region1)
local bitmap2=Bitmap.new(region2)
local bitmap3=Bitmap.new(region3)
local bitmap4=Bitmap.new(region4)

stage:addChild(bitmap1)
stage:addChild(bitmap2)
stage:addChild(bitmap3)
stage:addChild(bitmap4)

TextureRegion . new 2011.6+


Creates a new TextureRegion object.
TextureRegion.new(texture)
texture : (TextureBase) texture object

TextureRegion . new 2011.6+


Creates a new TextureRegion object.<ul><li>If TextureRegion object is created with 1 parameter (texture),
it specifies the whole texture.</li><li>If TextureRegion object is created with 5 parameters (texture, x, y,
width, height), if specifies a rectangular region within texture.</li></ul>
TextureRegion.new(texture, x, y, width, height)
texture : (TextureBase) texture object
x : (num) left coordinate of the region
y : (num) top coordinate of the region
width : (num) width of the region
height : (num) height of the region

TextureRegion . new 2011.6+


Creates a new TextureRegion object.
TextureRegion.new(texture)
texture : (TextureBase) texture object

TextureRegion . new 2011.6+

Gideros API Reference v2017.12 Page 103


Creates a new TextureRegion object.<ul><li>If TextureRegion object is created with 1 parameter (texture),
it specifies the whole texture.</li><li>If TextureRegion object is created with 5 parameters (texture, x, y,
width, height), if specifies a rectangular region within texture.</li></ul>
TextureRegion.new(texture, x, y, width, height)
texture : (TextureBase) texture object
x : (num) left coordinate of the region
y : (num) top coordinate of the region
width : (num) width of the region
height : (num) height of the region

TextureRegion : getRegion 2012.08.2+


Returns the coordinates of the region.
num, num, num, num = TextureRegion:getRegion()
num : x coordinate from texture
num : y coordinate from texture
num : width of region
num : height of region

TextureRegion : setRegion 2012.08.2+


Sets the coordinates of the region.
TextureRegion:setRegion(x, y, width, height)
x : (num) left coordinate of the region
y : (num) top coordinate of the region
width : (num) width of the region
height : (num) height of the region

Gideros API Reference v2017.12 Page 104


TileMap Inherits: Sprite 2011.6+
The `TileMap` class is used to work with tile maps easily and efficiently.Check `Desert` and `Sewers`
examples provided with Gideros for usage of TileMap with export from editor

TileMap . new 2011.6+


Creates a new `TileMap` instance.
TileMap.new(width, height, texture, tilewidth, tileheight, spacingx, spacingy, marginx, marginy, displaywidth,
displayheight)
width : (num) The width of the map in tiles
height : (num) The height of the map in tiles
texture : (TextureBase) The texture used in rendering tile map
tilewidth : (num) The width of a tile in pixels
tileheight : (num) The height of a tile in pixels
spacingx : (number, default = 0) The x-spacing in pixels between the tiles in this tileset
spacingy : (number, default = 0) The y-spacing in pixels between the tiles in this tileset
marginx : (number, default = 0) The x-margin from the top-left of the texture
marginy : (number, default = 0) The y-margin from the top-left of the texture
displaywidth : (number, default = tilewidth) The display width of a tile in pixels
displayheight : (number, default = tileheight) The display height of a tile in pixels

TileMap : clearTile 2011.6+


Set an empty tile at given indices. The tile indices are starting from 1.
TileMap:clearTile(x, y)
x : (num) The x-position of tile
y : (num) The y-position of tile

TileMap : getTile 2011.6+


Returns the index of the tile. The tile indices are starting from 1.
num, num, num = TileMap:getTile(x, y)

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

TileMap : setTile 2011.6+


Sets the index of the tile. The tile indices are starting from 1.
TileMap:setTile(x, y, tx, ty, flip)
x : (num) The x-position of tile
y : (num) The y-position of tile
tx : (num) The x-index of the tile
ty : (num) The y-index of the tile

Gideros API Reference v2017.12 Page 105


flip : (number, default = 0) flip flag of tile. Can be combination of TileMap.FLIP_HORIZONTAL,
TileMap.FLIP_VERTICAL and TileMap.FLIP_DIAGONAL

TileMap : shift 2011.6+


Shifts the tile map to change tile's graphic. The arguments are in tiles, not in pixels. By shifting the tile map
one by one as needed, you can create dynamic tile maps.
TileMap:shift(dx, dy)
dx : (num) The x amount of shift in tiles
dy : (num) The y amount of shift in tiles

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

Gideros API Reference v2017.12 Page 106


Timer Inherits: Object 2011.6+
The `Timer` class is used to execute a code at specified intervals. The listener functions are
registeredthrough `Event.TIMER` and `Event.TIMER_COMPLETE` events.

Timer . delayedCall 2011.6+


Provides a simple way to call a function after a set amount of time. This function returns the`Timer` object
created inside.
Timer = Timer.delayedCall(delay, func [, data])

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

Timer . new 2011.6+


Creates a new `Timer` object with the specified delay and repeatCount states.
Timer.new(delay, repeatCount)
delay : (any) The time interval between timer events in milliseconds.
repeatCount : (default = 0) The number of repetitions. A value of 0 runs the timer infinitely. If nonzero, the
timer runs the specified number of times and then stops.

Timer . pauseAll 2011.6+


Pause all timers. Suitable for temporarily pausing all timers when application is paused.
Timer.pauseAll()

Timer . resumeAll 2011.6+


Resume all timers.
Timer.resumeAll()

Timer . stopAll 2011.6+


Stop all timers.
Timer.stopAll()

Timer : getCurrentCount 2011.6+


Returns the current trigger count of the timer. It starts with 0 and if it reaches `repeatCount` value, timer
stops.
num = Timer:getCurrentCount()
num : The current repeat count.

Timer : getDelay 2011.6+

Gideros API Reference v2017.12 Page 107


Returns the time interval between timer events in milliseconds.
num = Timer:getDelay()
num : The time interval between timer events in milliseconds.

Timer : getRepeatCount 2011.6+


Returns the number of repetitions the timer will make. A value of 0 means the timer runs infinitely. If nonzero,
the timer runs the specified number of times and then stops.
num = Timer:getRepeatCount()
num : The number of repetitions.

Timer : isRunning 2011.6+


Returns the current running status of timer.
bool = Timer:isRunning()
bool : `true` if the timer is running, `false` otherwise.

Timer : reset 2011.6+


Stops the timer and sets the `currentCount` property to 0.
Timer:reset()

Timer : setDelay 2011.6+


Sets the time interval between timer events in milliseconds.
Timer:setDelay(delay)
delay : (num) The time interval between timer events in milliseconds.

Timer : setRepeatCount 2011.6+


Sets the number of repetitions the timer will make. A value of 0 means the timer runs infinitely. If nonzero, the
timer runs the specified number of times and then stops.
Timer:setRepeatCount(repeatCount)
repeatCount : (num) the number of repetitions the timer will make

Timer : start 2011.6+


Starts the timer.
Timer:start()

Timer : stop 2011.6+


Stops the timer. This function doesn't change the `currentCount` property.
Timer:stop()

Gideros API Reference v2017.12 Page 108


TTFont Inherits: FontBase 2011.6+
The `TTFont` class is used to load true type fonts.

Example:
local font=TTFont.new("tahoma.ttf", 30)

TTFont . new 2011.6+


Creates a new `TTFont` object.Starting from gideros 2017.9, 'text' optional parameter can be the empty
string, in which case Gideros will automatically cache characters as they are used.Also, 2017.9 allows
filename to be a table of several file names and associated size factor. Two forms are accepted:
{"font1.ttf","font2.ttf",..} or {{file="font1.ttf", sizeMult=1},{file="font2.ttf", sizeMult=1.1},...}.Characters will be
looked up in each file in sequence until a glyph is found.
TTFont.new(filename, size, text, filtering)
filename : (str) The name of the TTF file to be loaded
size : (num) size of the font
text : (string, optional) if specified, TTFont caches the characters of specified text to speed up the rendering
filtering : (boolean, default = false) Whether or not the font texture is filtered

Gideros API Reference v2017.12 Page 109


UrlLoader Inherits: Object 2012.2.2+
The `UrlLoader` class is used to download data from an URL. It can be used to download (and optionally
save) text files, XML files, JSON files, image files or binary files, etc.Downloaded data is delivered at
`event.data` field of `Event.COMPLETE` event as string. Lua is eight-bit clean and so strings may contain
characters with any numeric value, including embedded zeros. That means that you can store any binary
data into a string.<h3>HTTP Request Methods</h3>UrlLoader supports GET, POST, PUT and DELETE
methods. These are defined by these string constants:<ul><li>`UrlLoader.GET =
"get"`</li><li>`UrlLoader.POST = "post"`</li><li>`UrlLoader.PUT = "put"`</li><li>`UrlLoader.DELETE =
"delete"`</li></ul>

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


local out=io.open('|D|image.png', 'wb')
out:write(event.data)
out:close()

local b=Bitmap.new(Texture.new('|D|image.png'))
stage:addChild(b)
end

local function onError()


print('error')
end

local function onProgress(event)


print('progress: ' .. event.bytesLoaded .. ' of ' .. event.bytesTotal)
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..

Gideros API Reference v2017.12 Page 110


"\r\n--"..boundary.."--\r\n";

local headers={
["Content-Type"]="multipart/form-data; boundary="..boundary,
["Content-Length"]=#send,
}

local loader=UrlLoader.new("http://localhost/gideros.php", UrlLoader.POST, headers, send)

loader:addEventListener(Event.COMPLETE, function(e)
print(e.data)
end)

UrlLoader . new 2012.2.2+


Creates a new `UrlLoader` object.`url` parameter specifies the URL to download. This parameter is optional
and if specified loading starts immediately.`method` parameter specifies the HTTP request method. It can
be one of the values of `UrlLoader.GET`, `UrlLoader.POST`, `UrlLoader.PUT` or `UrlLoader.DELETE`.The
default HTTP method is `UrlLoader.GET`.`body` parameter specifies the HTTP body data. This parameter is
used only when the HTTP method is `UrlLoader.POST` or or `UrlLoader.PUT`.After loading is finished,
loaded data is stored at `event.data` field of `Event.COMPLETE` event as string.
UrlLoader.new(url, method, headers, body)
url : (string, optional) URL to download. This parameter is optional and if specified loading starts immediately.
method : (string, default = &quot;get&quot;) HTTP request method.
headers : (table, optional) HTTP headers.
body : (string, optional) HTTP body data. This data is sent as the message body of a request.

Example:
local url='http://www.[yourDomain].com/application.php?userid=gideros&amp;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')

UrlLoader : close 2012.2.2+


Terminates the current loading operation.
UrlLoader:close()

UrlLoader : ignoreSslErrors 2015.04.18+


Ignores SSL certificate related errors
UrlLoader:ignoreSslErrors()

Gideros API Reference v2017.12 Page 111


UrlLoader : load 2012.2.2+
Loads data from the specified URL. If there is any load operation in progress, it is terminated and new
progress starts.Please refer to [[UrlLoader.new]] for more detailed description of `url`, `method` and `body`
parameters.
UrlLoader:load(url, method, headers, body)
url : (string, optional) URL to download. This parameter is optional and if specified loading starts immediately.
method : (string, default = &quot;get&quot;) HTTP request method.
headers : (table, optional) HTTP headers.
body : (string, optional) HTTP body data. This data is sent as the message body of a request.

Gideros API Reference v2017.12 Page 112


Viewport Inherits: Sprite 2016.04+
A Viewport sprite allows to display another view of a tree hierarchy already on stage. Sprites can't have two
parents, but thanks to Viewport you can display the same Sprite twice on the stage. Useful for split screen
games, mini maps and so on.

Displaying same Bitmap in multiple views


-- content we want to display in multiple views
local content=Bitmap.new(Texture.new("ball.png"))

-- now setup view 1 as a 300x300 window


view1=Viewport.new()
view1:setClip(0,0,300,300)
view1:setContent(content)

-- add some transformations, just to see the difference


view1:setTransform(Matrix.new(1.7320507764816, -1.0000001192093, 1.0000001192093, 1.7320507764816,
50, 50))

-- add view to stage


stage:addChild(view1)

-- now setup view 2 as a 200x200 window


view2=Viewport.new()
view2:setClip(0,0,200,200)
view2:setPosition(0,300) -- lower down the screen
view2:setContent(content)

-- add some transformations, just to see the difference


view2:setTransform(Matrix.new(0.32139378786087, -0.38302224874496, 0.38302224874496,
0.32139378786087, 30, 30))

-- add view to stage


stage:addChild(view2)

Viewport : lookAngles BETA


Set up the transform matrix of this viewport taking eye position and pitch,yaw,roll angles as arguments
Viewport:lookAngles(eyex, eyey, eyez, pitch, yaw, roll)
eyex : (num) eye X coordinate
eyey : (num) eye Y coordinate
eyez : (num) eye Z coordinate
pitch : (num) pitch angle in degrees
yaw : (num) yaw angle in degrees
roll : (num) roll angle in degrees

Viewport : lookAt BETA


Set up the transform matrix of this viewport taking eye and target positions and up direction as arguments.
Viewport:lookAt(eyex, eyey, eyez, targetx, targety, targetz, upx, upy, upz)
eyex : (num) eye X coordinate

Gideros API Reference v2017.12 Page 113


eyey : (num) eye Y coordinate
eyez : (num) eye Z coordinate
targetx : (num) target X coordinate
targety : (num) target Y coordinate
targetz : (num) target Z coordinate
upx : (num) up X coordinate
upy : (num) up Y coordinate
upz : (num) up Z coordinate

Viewport : setContent 2016.04+


Specify which sprite should be displayed by this Viewport
Viewport:setContent(content)
content : (sprite) The sprite hierarchy to be displayed by this Viewport

Viewport : setProjection 2016.06+


Specify a projection matrix to use when displaying the content. Useful for rendering 3D worlds where units
are not related to screen dimensions, and where a perspective must be applied.
Viewport:setProjection(matrix)
matrix : (Matrix) Matrix to transform viewport

Viewport : setTransform 2016.04+


Specify a matrix by which the content will be transformed before being displayed.
Viewport:setTransform(transform)
transform : (Matrix) A Matrix object which will be applied to the content before display

Gideros API Reference v2017.12 Page 114


Physics API
This is a decription of liquid fun.

Gideros API Reference v2017.12 Page 115


b2 2011.6+
To load the Box2D library, call `require 'box2d'`. After loading Box2D library, `b2` table stores all classes and
functions related to Box2D physics library.

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)

Gideros API Reference v2017.12 Page 116


--create friction joint
local jointDef=b2.createFrictionJointDef(body, ground, 350, 200)
local frictionJoint=world:createJoint(jointDef)

--set maximum friction force to slow down the ball


frictionJoint:setMaxForce(100)

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

Gear joint combining revolute and prismatic joints


--create empty box2d body for joint
local ground=world:createBody({})

--create revolute joint


--note that ground should be passed as first parameter here
local jointDef=b2.createRevoluteJointDef(ground, body1, 300, 300)
local revoluteJoint=world:createJoint(jointDef)
--set motor
revoluteJoint:setMaxMotorTorque(1)
revoluteJoint:enableMotor(true)

--axisx, axisy values usually between 0 and 1


--note that ground should be passed as first parameter here
local jointDef=b2.createPrismaticJointDef(ground, body2, 350, 100, 0.3, 1)
local prismaticJoint=world:createJoint(jointDef)
--set motor
prismaticJoint:setMaxMotorForce(1)
prismaticJoint:enableMotor(true)

--create gear joint using two already created joints


local jointDef=b2.createGearJointDef(body1, body2, revoluteJoint, prismaticJoint, 1)
local gearJoint=world:createJoint(jointDef)

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

Gideros API Reference v2017.12 Page 117


table = b2.createMouseJointDef(bodyA, bodyB, targetx, targety, maxForce, frequencyHz, dampingRatio)

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

--joint with dummy body


local mouseJoint=nil

-- create a mouse joint on mouse down


function self:onMouseDown(event)
local jointDef=b2.createMouseJointDef(ground, body, event.x, event.y, 100000)
mouseJoint=world:createJoint(jointDef)
end

-- update the target of mouse joint on mouse move


function self:onMouseMove(event)
if mouseJoint ~= nil then
mouseJoint:setTarget(event.x, event.y)
end
end

-- destroy the mouse joint on mouse up


function self:onMouseUp(event)
if mouseJoint ~= nil then
world:destroyJoint(mouseJoint)
mouseJoint=nil
end
end

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

Gideros API Reference v2017.12 Page 118


axisx : (num) the x coordinate of the world axis
axisy : (num) the y coordinate of the world axis

Result:
table : A new prismatic joint definition table

Prismatic joint
--create empty box2d body for joint
local ground=world:createBody({})
ground:setPosition(465, 480)

--axisx, axisy values usually between 0 and 1


--0 0 moves freely
--0 1 moves on y axis
--1 0 moves on x axis
--1 1 moves on diagonal
local jointDef=b2.createPrismaticJointDef(body, ground, 350, 100, 0.3, 1)
local prismaticJoint=world:createJoint(jointDef)

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

local jointDef=b2.createPulleyJointDef(body1, body2,


200, 100, --coordinates where "imaginary string" is attached in the air for body 1
350, 100, --coordinates where "imaginary string" is attached in the air for body 2

Gideros API Reference v2017.12 Page 119


200, 300, --coordinates where "imaginary string" is attached to the body 1
350, 300, --coordinates where "imaginary string" is attached in the body 2
1) -- ratio (if < 1 -> makes body 2 heavier, > 1 makes body 1 heavier, =1 makes them equal
local pulleyJoint=world:createJoint(jointDef)

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)

local jointDef=b2.createRevoluteJointDef(body, ground, 300, 300)


local revoluteJoint=world:createJoint(jointDef)
--will not let ball spin for ever
revoluteJoint:setMaxMotorTorque(1)
revoluteJoint:enableMotor(true)

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

Gideros API Reference v2017.12 Page 120


b2 . createWeldJointDef 2011.6+
Creates and returns a weld joint definition table with the bodies, 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 weld joint).
table = b2.createWeldJointDef(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 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)

--axisx, axisy values usually between 0 and 1


--0 0 moves freely
--0 1 force pulling back on y axis
--1 0 force pulling back on x axis
--1 1 force pulling back all diretions
local jointDef=b2.createWheelJointDef(body, ground, 350, 200, 1, 1)
local wheelJoint=world:createJoint(jointDef)

b2 . getScale 2011.6+

Gideros API Reference v2017.12 Page 121


Returns the global pixels to meters scale (Please refer to [[b2.setScale]] function for more information about
pixels to meters scaling).
num = b2.getScale()
num : The global pixels to meters scale

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

Gideros API Reference v2017.12 Page 122


b2.Body 2011.6+
A rigid body. These are created via `b2.World:createBody`.

Creating Box2d body and moving Bitmap along the body


require "box2d"
local world=b2.World.new(0, 10, true)

--create ball bitmap object from ball graphic


local ball=Bitmap.new(Texture.new("ball.png"))
--reference center of the ball for positioning
ball:setAnchorPoint(0.5,0.5)

ball:setPosition(100,100)

--get radius
local radius=ball:getWidth()/2

--create box2d physical object


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

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

b2 . Body : applyAngularImpulse 2011.6+


Applies an angular impulse.
b2.Body:applyAngularImpulse(impulse)
impulse : (num) the angular impulse in units of kg*m*m/s

b2 . Body : applyForce 2011.6+


Applies a force at a world point. If the force is notapplied at the center of mass, it will generate a torque
andaffect the angular velocity. This wakes up the body.
b2.Body:applyForce(forcex, forcey, pointx, pointy)
forcex : (num)
forcey : (num)
pointx : (num) the x coordinate of the world position of the point of application
pointy : (num) the y coordinate of the world position of the point of application

Gideros API Reference v2017.12 Page 123


b2 . Body : applyLinearImpulse 2011.6+
Applies an impulse at a point. This immediately modifies the velocity. It alsomodifies the angular velocity if
the point of application is not at the center ofmass. This wakes up the body.
b2.Body:applyLinearImpulse(impulsex, impulsey, pointx, pointy)
impulsex : (num) the x coordinate of the world impulse vector, usually in N-seconds or kg-m/s
impulsey : (num) the y coordinate of the world impulse vector, usually in N-seconds or kg-m/s
pointx : (num) the x coordinate of the world position of the point of application
pointy : (num) the y coordinate of the world position of the point of application

b2 . Body : applyTorque 2011.6+


Applies a torque. This affects the angular velocity without affectingthe linear velocity of the center of mass.
This wakes up the body.
b2.Body:applyTorque(torque)
torque : (num) , usually in N-m

b2 . Body : createFixture 2011.6+


Creates a fixture and attach it to this body. If the density is non-zero, this function automaticallyupdates the
mass of the body. Contacts are not created until the next time step. The fixture definition is givenas a
ordinary table. The fields of the fixture definition table are:<ul><li>`shape`: (b2.Shape) The shape, this must
be set.</li><li>`friction`: (number) The friction coefficient, usually in the range [0,1].</li><li>`restitution`:
(number) The restitution (elasticity) usually in the range [0,1].</li><li>`density`: (number) The density, usually
in kg/m^2.</li><li>`isSensor`: (boolean) A sensor shape collects contact information but never generates a
collision response.</li><li>`filter`: (table) Contact filtering data. The definition of contact filtering data is given
at `b2.Fixture:setFilterData` function.</li></ul>The unset fields gets default values.<ul><li>`Warning`: This
function is locked during callbacks.</li></ul>
b2.Fixture = b2.Body:createFixture(fixtureDef)

Parameter:
fixtureDef : (table)

Result:
b2.Fixture : The created fixture instance.

b2 . Body : destroyFixture 2011.6+


Destroy a fixture. This removes the fixture from the broad-phase and destroys allcontacts associated with
this fixture. This will automatically adjust the mass of the body if thebody is dynamic and the fixture has
positive density. All fixtures attached to a body are implicitlydestroyed when the body is
destroyed.<ul><li>*Warning:** This function is locked during callbacks.</li></ul>
b2.Body:destroyFixture(fixture)
fixture : (b2.Fixture) the fixture to be removed

b2 . Body : getAngle 2011.6+


Returns the current world rotation angle in radians.
num = b2.Body:getAngle()
num : Current body angle in radians

Gideros API Reference v2017.12 Page 124


b2 . Body : getAngularDamping 2012.2.2+
Returns the angular damping of the body.
num = b2.Body:getAngularDamping()
num : The angular damping of the body

b2 . Body : getAngularVelocity 2011.6+


Returns the angular velocity.
num = b2.Body:getAngularVelocity()
num : Angular velocity in radians/second

b2 . Body : getGravityScale 2012.2.2.1+


Returns the gravity scale of the body.
num = b2.Body:getGravityScale()
num : The gravity scale of the body

b2 . Body : getInertia 2012.2.2+


Returns the rotational inertia of the body about the local origin in kg-m^2.
num = b2.Body:getInertia()
num : The rotational inertia of the body about the local origin in kg-m^2.

b2 . Body : getLinearDamping 2012.2.2+


Returns the linear damping of the body.
num = b2.Body:getLinearDamping()
num : The linear damping of the body

b2 . Body : getLinearVelocity 2011.6+


Returns the linear velocity of the center of mass.
num, num = b2.Body:getLinearVelocity()
num : x vector of the linear velocity
num : y vector of the linear velocity

b2 . Body : getLocalCenter 2012.2.2+


Returns the local position of the center of mass.
num, num = b2.Body:getLocalCenter()
num : x coordinate of the local position of the center of mass
num : x coordinate of the local position of the center of mass

b2 . Body : getLocalPoint 2012.09.6+


Returns the local coordinates of a point given the world coordinates.
num, num = b2.Body:getLocalPoint(x, y)

Gideros API Reference v2017.12 Page 125


Parameters:
x : (num) x coordinate of the world point
y : (num) y coordinate of the world point

Results:
num : x coordinate of the provided point expressed in local coordinates
num : y coordinate of the provided point expressed in local coordinates

b2 . Body : getLocalVector 2012.09.6+


Returns the local coordinates of a vector given the world coordinates.
num, num = b2.Body:getLocalVector(x, y)

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

b2 . Body : getMass 2012.2.2+


Returns the total mass of the body in kilograms (kg).
num = b2.Body:getMass()
num : The total mass of the body in kilograms (kg)

b2 . Body : getPosition 2011.6+


Returns the world body origin position.
num, num = b2.Body:getPosition()
num : x coordinate of the body position
num : y coordinate of the body position

b2 . Body : getWorldCenter 2012.2.2+


Returns the world position of the center of mass.
num, num = b2.Body:getWorldCenter()
num : x coordinate of the world position of the center of mass
num : x coordinate of the world position of the center of mass

b2 . Body : getWorldPoint 2012.09.6+


Returns the world coordinates of a point given the local coordinates.
num, num = b2.Body:getWorldPoint(x, y)

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

Gideros API Reference v2017.12 Page 126


b2 . Body : getWorldVector 2012.09.6+
Returns the world coordinates of a vector given the local coordinates.
num, num = b2.Body:getWorldVector(x, y)

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

b2 . Body : isActive 2011.6+


Returns the active state of the body.
bool = b2.Body:isActive()
bool : `true` if the body is active, `false` otherwise

b2 . Body : isAwake 2011.6+


Returns the sleeping state of this body. Returns `true` if body is awake (not sleeping), `false` otherwise.
bool = b2.Body:isAwake()
bool : The sleeping state of this body.

b2 . Body : isBullet 2012.09.6+

bool = b2.Body:isBullet()
bool : if body is set to behave bullet

b2 . Body : isFixedRotation 2012.09.6+

bool = b2.Body:isFixedRotation()
bool : if body has fixed rotation set

b2 . Body : isSleepingAllowed 2012.09.6+

bool = b2.Body:isSleepingAllowed()
bool : if body is allowed to sleep

b2 . Body : setActive 2011.6+


Sets the active state of the body. An inactive body is not simulated and cannot be collided with or woken up.
If you pass a flag of true, all fixtures will be added to the broad-phase. If you pass a flag of false,all fixtures
will be removed from the broad-phase and all contacts will be destroyed. Fixtures and joints are otherwise
unaffected. You may continue to create/destroy fixtures and joints on inactive bodies. Fixtures on an inactive
body are implicitly inactive and will not participate in collisions, ray-casts, or queries. Joints connected to an
inactive body are implicitly inactive. An inactive body is still owned by a [[b2.World]] object and remains in the

Gideros API Reference v2017.12 Page 127


body list.
b2.Body:setActive(flag)
flag : (bool) active flag

b2 . Body : setAngle 2011.6+


Sets the current world rotation angle in radians.
b2.Body:setAngle(angle)
angle : (num) world rotation angle in radians

b2 . Body : setAngularDamping 2012.2.2+


Sets the angular damping of the body.
b2.Body:setAngularDamping(angularDamping)
angularDamping : (num) new angular damping of the body

b2 . Body : setAngularVelocity 2011.6+


Sets the angular velocity.
b2.Body:setAngularVelocity(omega)
omega : (num) the new angular velocity in radians/second

b2 . Body : setAwake 2012.2.2.1+


Set the sleep state of the body. A sleeping body has very low CPU cost.
b2.Body:setAwake(awake)
awake : (bool) set to true to wake body, false to put it to sleep

b2 . Body : setBullet 2012.09.6+

b2.Body:setBullet(flag)
flag : (bool)

b2 . Body : setFixedRotation 2012.09.6+

b2.Body:setFixedRotation(flag)
flag : (bool)

b2 . Body : setGravityScale 2012.2.2.1+


Sets the gravity scale of the body.
b2.Body:setGravityScale(scale)
scale : (num) new gravity scale of the body

b2 . Body : setLinearDamping 2012.2.2+

Gideros API Reference v2017.12 Page 128


Sets the linear damping of the body.
b2.Body:setLinearDamping(linearDamping)
linearDamping : (num) new linear damping of the body

b2 . Body : setLinearVelocity 2011.6+


Sets the linear velocity of the center of mass.
b2.Body:setLinearVelocity(x, y)
x : (num) x coordinate of the linear velocity
y : (num) y coordinate of the linear velocity

b2 . Body : setPosition 2011.6+


Sets the world body origin position.
b2.Body:setPosition(x, y)
x : (num) x coordinate of the position
y : (num) y coordinate of the position

b2 . Body : setSleepingAllowed 2012.09.6+

b2.Body:setSleepingAllowed(flag)
flag : (bool)

Gideros API Reference v2017.12 Page 129


b2.ChainShape Inherits: b2.Shape 2012.2.2+
A chain shape is a free form sequence of line segments. The chain has two-sided collision, so you can use
inside and outside collision. Therefore, you may use any winding order. Connectivity information is used to
create smooth collisions.<ul><li>*Note:** The chain will not collide properly if there are
self-intersections.</li></ul>

Create world bounds using ChainShape


local body=world:createBody{type=b2.STATIC_BODY}
body:setPosition(0, 0)
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}

b2 . ChainShape . new 2011.6+


Creates a new `b2.ChainShape` object.
b2.ChainShape.new()

b2 . ChainShape : createChain 2011.6+


Creates a chain with isolated end vertices.
b2.ChainShape:createChain(vertices)
vertices : (any) A list of numbers that contains the x, y coordinates of the vertices sequentially

b2 . ChainShape : createLoop 2011.6+


Creates a loop. This automatically adjusts connectivity.
b2.ChainShape:createLoop(vertices)
vertices : (any) A list of numbers that contains the x, y coordinates of the vertices sequentially

Gideros API Reference v2017.12 Page 130


b2.CircleShape Inherits: b2.Shape 2011.6+
A circle shape.

Creating a circle body


--create ball bitmap object from ball graphic
local ball=Bitmap.new(Texture.new("./ball.png"))
--reference center of the ball for positioning
ball:setAnchorPoint(0.5,0.5)

ball:setPosition(x,y)

--get radius
local radius=ball:getWidth()/2

--create box2d physical object


local body=world:createBody{type=b2.DYNAMIC_BODY}
body:setPosition(ball:getX(), ball:getY())
body:setAngle(ball:getRotation()*math.pi/180)
local circle=b2.CircleShape.new(0, 0, radius)
local fixture=body:createFixture{shape=circle, density=1.0,
friction=0.1, restitution=0.2}

b2 . CircleShape . new 2011.6+


Creates a new `b2.CircleShape` instance and optionally set its center point and radius.If this function is
called with more than 3 parameters, `b2.CircleShape` instanceis created and its center point and radius are
set. If this function is called without any paramaters, only `b2.CircleShape` instance is created and you
should set the centerpoint and radius with [[b2.CircleShape:set]] function.
any, any = b2.CircleShape.new(centerx, centery, radius)

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.

b2 . CircleShape : set 2011.6+


Sets the center point and radius of this instance.
b2.CircleShape:set(centerx, centery, radius)
centerx : (number, optional) the x coordinate of the center
centery : (number, optional) the y coordinate of the center
radius : (number, optional) the radius

Gideros API Reference v2017.12 Page 131


b2.Contact 2012.09.6+
The class manages contact between two shapes. A contact exists for each overlapping AABB in the
broad-phase (except if filtered). Therefore a contact object may exist that has no contact points.

Checking collisions from bottom using b2.Contact


local isTouchingGround=false
world:addEventListener(Event.BEGIN_CONTACT, function(e)
local manifold=e.contact:getWorldManifold()
if manifold.normal.y > 0.9 then
--collision came from bottom
isTouchingGround=true
end
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)

b2 . Contact : getChildIndexA 2012.09.6+


Returns the child primitive index for fixture A.
num = b2.Contact:getChildIndexA()
num : Returns the child primitive index for fixture A.

b2 . Contact : getChildIndexB 2012.09.6+


Returns the child primitive index for fixture B.
num = b2.Contact:getChildIndexB()
num : Returns the child primitive index for fixture B.

b2 . Contact : getFixtureA 2012.09.6+


Returns fixture A in this contact.
b2.Fixture = b2.Contact:getFixtureA()
b2.Fixture : Fixture A in this contact.

b2 . Contact : getFixtureB 2012.09.6+


Returns fixture B in this contact.
b2.Fixture = b2.Contact:getFixtureB()
b2.Fixture : Fixture B in this contact.

b2 . Contact : getFriction 2012.09.6+


Returns the friction.

Gideros API Reference v2017.12 Page 132


num = b2.Contact:getFriction()
num : The friction.

b2 . Contact : getManifold 2012.09.6+


Returns the contact manifold as a table. This table contains `points`, `localNormal`, `localPoint` and `type`
fields.
b2.Manifold = b2.Contact:getManifold()
b2.Manifold : the manifold of contact

b2 . Contact : getRestitution 2012.09.6+


Returns the restitution.
num = b2.Contact:getRestitution()
num : The restitution.

b2 . Contact : getWorldManifold 2012.09.6+


Returns the world manifold as a table. This table contains `normal` and `points` fields.
b2.WorldManifold = b2.Contact:getWorldManifold()
b2.WorldManifold : Information about contact between 2 bodies relative to the world

b2 . Contact : isTouching 2012.09.6+


Returns whether the contact is touching or not.
bool = b2.Contact:isTouching()
bool : Whether the contact is touching or not.

b2 . Contact : resetFriction 2012.09.6+


Resets the friction mixture to the default value.
b2.Contact:resetFriction()

b2 . Contact : resetRestitution 2012.09.6+


Resets the restitution mixture to the default value.
b2.Contact:resetRestitution()

b2 . Contact : setEnabled 2012.09.6+


Enables/disables the contact. This can be used inside the pre-solve contact listener. The contact is only
disabled for the current time step (or sub-step in continuous collisions).
b2.Contact:setEnabled(flag)
flag : (bool)

b2 . Contact : setFriction 2012.09.6+


Overrides the default friction mixture. You can call this in pre-solve event. This value persists until set or

Gideros API Reference v2017.12 Page 133


reset.
b2.Contact:setFriction(friction)
friction : (num)

b2 . Contact : setRestitution 2012.09.6+


Overrides the default restitution mixture. You can call this in pre-solve event. This value persists until set or
reset.
b2.Contact:setRestitution(restitution)
restitution : (num)

Gideros API Reference v2017.12 Page 134


b2.DebugDraw Inherits: Sprite 2011.6+
The `b2.DebugDraw` class is used to provide debug drawing of physical entities in your application.

Example:
local debugDraw=b2.DebugDraw.new()
world:setDebugDraw(debugDraw)
stage:addChild(debugDraw)

b2 . DebugDraw . new 2011.6+


Creates a new `b2.DebugDraw` instance.
b2.DebugDraw.new()

b2 . DebugDraw : appendFlags 2011.6+


Append flags to the current flags.
b2.DebugDraw:appendFlags(flags)
flags : (num) debug draw flags

b2 . DebugDraw : clearFlags 2011.6+


Clear flags from the current flags.
b2.DebugDraw:clearFlags(flags)
flags : (num) debug draw flags

b2 . DebugDraw : getFlags 2011.6+


Returns the debug drawing flags.
num = b2.DebugDraw:getFlags()
num : The debug drawing flags

b2 . DebugDraw : setFlags 2011.6+


Sets the debug drawing flags. These flags are
available:<ul><li>`b2.DebugDraw.SHAPE_BIT`</li><li>`b2.DebugDraw.JOINT_BIT`</li><li>`b2.DebugDra
w.AABB_BIT`</li><li>`b2.DebugDraw.PAIR_BIT`</li><li>`b2.DebugDraw.CENTER_OF_MASS_BIT`</li></
ul>`b2.DebugDraw.SHAPE_BIT` is set by default. Because Lua doesn't support bitwise operations by
default, you can use ` ` operator to combine flags.
b2.DebugDraw:setFlags(flags)
flags : (num) debug draw flags

Example:
local debugDraw=b2.DebugDraw.new()
debugDraw:setFlags(b2.DebugDraw.SHAPE_BIT b2.DebugDraw.JOINT_BIT)

Gideros API Reference v2017.12 Page 135


b2.DistanceJoint Inherits: b2.Joint 2011.6+
A distance joint constrains two points on two bodies to remain at a fixed distance from each other. You can
view this as a massless, rigid rod.

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 . DistanceJoint : getDampingRatio 2011.6+


Returns the damping ratio of this distance joint.
num = b2.DistanceJoint:getDampingRatio()
num : The damping ratio of this distance joint

b2 . DistanceJoint : getFrequency 2011.6+


Returns the mass-spring-damper frequency of this distance joint in Hertz.
num = b2.DistanceJoint:getFrequency()
num : The mass-spring-damper frequency in Hertz.

b2 . DistanceJoint : getLength 2011.6+


Returns the length of this distance joint, usually in meters.
num = b2.DistanceJoint:getLength()
num : The length of this distance joint, usually in meters

b2 . DistanceJoint : setDampingRatio 2011.6+


Sets the damping ratio of this distance joint. 0 = no damping, 1 = critical damping.
b2.DistanceJoint:setDampingRatio(ratio)
ratio : (num) the damping ratio

b2 . DistanceJoint : setFrequency 2011.6+


Sets the mass-spring-damper frequency in Hertz.
b2.DistanceJoint:setFrequency(frequency)
frequency : (num) the mass-spring-damper frequency in Hertz

b2 . DistanceJoint : setLength 2011.6+


Sets the natural length. Manipulating the length can lead to non-physical behavior when the frequency is
zero.

Gideros API Reference v2017.12 Page 136


b2.DistanceJoint:setLength(length)
length : (num) the length of this distance joint, usually in meters.

Gideros API Reference v2017.12 Page 137


b2.EdgeShape Inherits: b2.Shape 2011.6+
A line segment (edge) shape. These can be connected in chains or loops to other edge shapes.

b2 . EdgeShape . new 2011.6+


Creates a new `b2.EdgeShape` instance and optionally sets its 2 vertices. If this function is called with more
than 4 parameters, `b2.EdgeShape` instanceis created and its 2 vertices are set. If this function is called
without any paramaters, only `b2.EdgeShape` instance is created and you should set the 2 vertices with
[[b2.EdgeShape:set]] function.
b2.EdgeShape.new(v1x, v1y, v2x, v2y)
v1x : (number, optional) - the x coordinate of 1st point of edge
v1y : (number, optional) - the y coordinate of 1st point of edge
v2x : (number, optional) - the x coordinate of 2nd point of edge
v2y : (number, optional) - the y coordinate of 2nd point of edge

b2 . EdgeShape : set 2011.6+


Sets the two vertices of this instance.
b2.EdgeShape:set(v1x, v1y, v2x, v2y)
v1x : (num) - the x coordinate of 1st point of edge
v1y : (num) - the y coordinate of 1st point of edge
v2x : (num) - the x coordinate of 2nd point of edge
v2y : (num) - the y coordinate of 2nd point of edge

Gideros API Reference v2017.12 Page 138


b2.Fixture 2011.6+
A fixture is used to attach a shape to a body for collision detection. A fixture inherits itstransform from its
parent. Fixtures hold additional non-geometric data such as friction, collision filters, etc.Fixtures are created
via `b2.Body:createFixture`.

Example of fixtures collision filtering


local BALL_MASK=1
local CRATE_MASK=2
local WALL_MASK=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})

b2 . Fixture : getBody 2011.6+


Returns the parent body of this fixture. This is `nil` if the fixture is not attached.
b2.Body = b2.Fixture:getBody()
b2.Body : body that created the fixture

b2 . Fixture : getFilterData 2011.6+


Returns the contact filtering data.
table = b2.Fixture:getFilterData()
table : contact filtering data table

Gideros API Reference v2017.12 Page 139


b2 . Fixture : isSensor 2011.6+
Is this fixture a sensor (non-solid)?
any, any = b2.Fixture:isSensor()
any : `true` if the shape is a sensor, `false` otherwise.
any : `true` if the shape is a sensor, `false` otherwise.

b2 . Fixture : setFilterData 2011.6+


Sets the contact filtering data. This will not update contacts until the next time stepwhen either parent body is
active and awake. The filter data definition is givenas a ordinary table. The fields of the filter data table
are:<ul><li>`categoryBits`: (number) The collision category bits. Normally you would just set one
bit.</li><li>`maskBits`: (number) The collision mask bits. This states the categories that this shape would
accept for collision.</li><li>`groupIndex`: (number) Collision groups allow a certain group of objects to never
collide (negative) or always collide (positive). Zero means no collision group. Non-zero group filtering always
wins against the mask bits.</li></ul>
b2.Fixture:setFilterData(filterData)
filterData : (table)

Example of fixtures collision filtering


local BALL_MASK=1
local CRATE_MASK=2
local WALL_MASK=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})

Gideros API Reference v2017.12 Page 140


b2 . Fixture : setSensor 2011.6+
Sets if this fixture is a sensor.
b2.Fixture:setSensor(sensor)
sensor : (bool)

Gideros API Reference v2017.12 Page 141


b2.FrictionJoint Inherits: b2.Joint 2011.6+
Friction joint. This is used for top-down friction. It provides 2D translational friction and angular friction.

Friction joint
--create empty box2d body for joint
local ground=world:createBody({})
ground:setPosition(350, 480)

--create friction joint


local jointDef=b2.createFrictionJointDef(body, ground, 350, 200)
local frictionJoint=world:createJoint(jointDef)

--set maximum friction force to slow down the ball


frictionJoint:setMaxForce(100)

b2 . FrictionJoint : getMaxForce 2011.6+


Returns the maximum friction force in N.
num = b2.FrictionJoint:getMaxForce()
num : The maximum friction force in N

b2 . FrictionJoint : getMaxTorque 2011.6+


Returns the maximum friction torque in N*m.
num = b2.FrictionJoint:getMaxTorque()
num : The maximum friction torque in N*m

b2 . FrictionJoint : setMaxForce 2011.6+


Sets the maximum friction force in N.
b2.FrictionJoint:setMaxForce(force)
force : (num) the maximum friction force in N

b2 . FrictionJoint : setMaxTorque 2011.6+


Sets the maximum friction torque in N*m.
b2.FrictionJoint:setMaxTorque(torque)
torque : (num) the maximum friction torque in N*m

Gideros API Reference v2017.12 Page 142


b2.GearJoint Inherits: b2.Joint 2011.6+
A gear joint is used to connect two joints together. Either joint can be a revolute or prismatic joint. You specify
a gear ratio to bind the motions together: coordinate1 ratio * coordinate2 = constant The ratio can be
negative or positive. If one joint is a revolute joint and the other joint is a prismatic joint, then the ratio will
have units of length or units of 1/length.

Gear joint combining revolute and prismatic joints


--create empty box2d body for joint
local ground=world:createBody({})

--create revolute joint


--note that ground should be passed as first parameter here
local jointDef=b2.createRevoluteJointDef(ground, body1, 300, 300)
local revoluteJoint=world:createJoint(jointDef)
--set motor
revoluteJoint:setMaxMotorTorque(1)
revoluteJoint:enableMotor(true)

--axisx, axisy values usually between 0 and 1


--note that ground should be passed as first parameter here
local jointDef=b2.createPrismaticJointDef(ground, body2, 350, 100, 0.3, 1)
local prismaticJoint=world:createJoint(jointDef)
--set motor
prismaticJoint:setMaxMotorForce(1)
prismaticJoint:enableMotor(true)

--create gear joint using two already created joints


local jointDef=b2.createGearJointDef(body1, body2, revoluteJoint, prismaticJoint, 1)
local gearJoint=world:createJoint(jointDef)

b2 . GearJoint : getRatio 2011.6+


Returns the gear ratio.
num = b2.GearJoint:getRatio()
num : The gear ratio

b2 . GearJoint : setRatio 2011.6+


Sets the gear ratio.
b2.GearJoint:setRatio(ratio)
ratio : (num) the gear ratio

Gideros API Reference v2017.12 Page 143


b2.Joint 2011.6+
The `b2.Joint` class is the base joint class. Joints are used to constraint two bodies together in various
fashions. Some joints also feature limits and motors.

b2 . Joint : getAnchorA 2011.6+


Returns the anchor point on bodyA in world coordinates.
num, num = b2.Joint:getAnchorA()
num : x coordinate of the anchor point
num : y coordinate of the anchor point

b2 . Joint : getAnchorB 2011.6+


Returns the anchor point on bodyB in world coordinates.
num, num = b2.Joint:getAnchorB()
num : x coordinate of the anchor point
num : y coordinate of the anchor point

b2 . Joint : getBodyA 2011.6+


Returns the first body attached to this joint.
b2.Body = b2.Joint:getBodyA()
b2.Body : The first body attached to this joint

b2 . Joint : getBodyB 2011.6+


Returns the second body attached to this joint.
b2.Body = b2.Joint:getBodyB()
b2.Body : The second body attached to this joint

b2 . Joint : getReactionForce 2011.6+


Returns the reaction force on bodyB at the joint anchor in Newtons.
num, num = b2.Joint:getReactionForce(inv_dt)

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

b2 . Joint : getReactionTorque 2011.6+


Returns the reaction torque on bodyB in N*m.
num = b2.Joint:getReactionTorque(inv_dt)

Parameter:
inv_dt : (num)

Result:

Gideros API Reference v2017.12 Page 144


num : The reaction torque on bodyB in N*m

b2 . Joint : getType 2011.6+


Returns the type of the concrete joint. The return value can be one of the `b2.REVOLUTE_JOINT`,
`b2.PRISMATIC_JOINT`, `b2.DISTANCE_JOINT`, `b2.PULLEY_JOINT`,`b2,MOUSE_JOINT`,
`b2.GEAR_JOINT`, `b2.LINE_JOINT`, `b2.WELD_JOINT`, `b2.FRICTION_JOINT`, `b2.ROPE_JOINT`.
str = b2.Joint:getType()
str : The type of the joint

b2 . Joint : isActive 2011.6+


Short-cut function to determine if either body is inactive.
bool = b2.Joint:isActive()
bool : `true` if both bodyA and bodyB is active, `false` otherwise

Gideros API Reference v2017.12 Page 145


b2.Manifold 2012.09.6+
Holds the local information about contact between 2 bodies

Example content of b2.Manifold


[localNormal] => Table {
{
[y] => -1
[x] => -0
}
[points] => Table {
{
[1] => Table {
{
[normalImpulse] => 0
[localPoint] => Table {
{
[y] => 0
[x] => 0
}
[tangentImpulse] => 0
}
}
[localPoint] => Table {
{
[y] => 320.00000953674
[x] => 480
}

Gideros API Reference v2017.12 Page 146


b2.MouseJoint Inherits: b2.Joint 2011.6+
A mouse joint is used to make a point on a body track a specified world point. This a soft constraint with a
maximum force. This allows the constraint to stretch and without applying huge forces.

Mouse joint
--create empty box2d body for joint
local ground=world:createBody({})

--joint with dummy body


local mouseJoint=nil

-- create a mouse joint on mouse down


function self:onMouseDown(event)
local jointDef=b2.createMouseJointDef(ground, body, event.x, event.y, 100000)
mouseJoint=world:createJoint(jointDef)
end

-- update the target of mouse joint on mouse move


function self:onMouseMove(event)
if mouseJoint ~= nil then
mouseJoint:setTarget(event.x, event.y)
end
end

-- destroy the mouse joint on mouse up


function self:onMouseUp(event)
if mouseJoint ~= nil then
world:destroyJoint(mouseJoint)
mouseJoint=nil
end
end

b2 . MouseJoint : getDampingRatio 2011.6+


Returns the damping ratio. 0 = no damping, 1 = critical damping.
num = b2.MouseJoint:getDampingRatio()
num : The damping ratio

b2 . MouseJoint : getFrequency 2011.6+


Returns the response speed in Hertz.
num = b2.MouseJoint:getFrequency()
num : The response speed in Hertz

b2 . MouseJoint : getMaxForce 2011.6+


Returns the maximum force in Newtons.
num = b2.MouseJoint:getMaxForce()
num : The maximum force in Newtons.

Gideros API Reference v2017.12 Page 147


b2 . MouseJoint : getTarget 2011.6+
Returns the x and y coordinates of the target point.
num, num = b2.MouseJoint:getTarget()
num : x coordinate of the target point
num : y coordinate of the target point

b2 . MouseJoint : setDampingRatio 2011.6+


Sets the damping ratio. 0 = no damping, 1 = critical damping.
b2.MouseJoint:setDampingRatio(ratio)
ratio : (num) the damping ratio

b2 . MouseJoint : setFrequency 2011.6+


Sets the response speed in Hertz.
b2.MouseJoint:setFrequency(frequency)
frequency : (num) the response speed in Hertz

b2 . MouseJoint : setMaxForce 2011.6+


Sets the maximum force in Newtons.
b2.MouseJoint:setMaxForce(force)
force : (num) the maximum force in Newtons

b2 . MouseJoint : setTarget 2011.6+


Updates the target point.
b2.MouseJoint:setTarget(x, y)
x : (num) x coordinate of the target point
y : (num) y coordinate of the target point

Gideros API Reference v2017.12 Page 148


b2.ParticleSystem 2015.06.30+
Defines particle system in box2d world using Liquid fun

Simple particle system example


-- create world
local world=b2.World.new(0, 9.8)

local ps1= world:createParticleSystem({ radius=5})


ps1:setTexture(Texture.new("Bubble.png"))
stage:addChild(ps1)

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)

b2 . ParticleSystem : containsParticle BETA


Returns true of particle is within the particle system
bool = b2.ParticleSystem:containsParticle(id)

Parameter:
id : (num) Particle id

Result:
bool : True if the particle is within the particle system else false.

b2 . ParticleSystem : createParticle 2015.06.30+


Creates new particle.Accepts table with possible keys:"flags", "position","velocity", "color", "alpha"and returns
particle id
num = b2.ParticleSystem:createParticle(particleDef)

Parameter:
particleDef : (table) table with particle data

Gideros API Reference v2017.12 Page 149


Result:
num : particle id

b2 . ParticleSystem : createParticleGroup 2011.6+


Create group of multiple particles with same properties, that can be defined in table
with:"flags""groupFlags""position""angle""linearVelocity""angularVelocity""color""alpha""strength""shape""lifeti
me"
b2.ParticleSystem:createParticleGroup(particleGoupDef)
particleGoupDef : (table) table with particle group data

b2 . ParticleSystem : destroyParticle 2015.06.30+


Destroy particle by Id
b2.ParticleSystem:destroyParticle(id)
id : (num) id of particle to destroy

b2 . ParticleSystem : destroyParticles BETA


Destroys particles
b2.ParticleSystem:destroyParticles(ids)
ids : (table) List of particle ids to destroy

b2 . ParticleSystem : getParticleCount BETA


Returns the number of particles
num = b2.ParticleSystem:getParticleCount()
num : The number of particles

b2 . ParticleSystem : getParticleGroupList 2011.6+


Returns a list of particle groups.
b2.ParticleSystem:getParticleGroupList()

b2 . ParticleSystem : setTexture 2015.06.30+


Sets texture to particles in this system
b2.ParticleSystem:setTexture(texture)
texture : (Texture) texture to use for particles

Gideros API Reference v2017.12 Page 150


b2.PolygonShape Inherits: b2.Shape 2011.6+
A convex polygon. It is assumed that the interior of the polygon is to the left of each edge.

Create a square box2d box


--create box2d physical object
local body=world:createBody{type=b2.STATIC_BODY}
local poly=b2.PolygonShape.new()
poly:setAsBox(100, 100)
local fixture=body:createFixture{shape=poly, density=1.0,
friction=0.1, restitution=0.2}

b2 . PolygonShape . new 2011.6+


Creates a new `b2.PolygonShape` instance.
any, any = b2.PolygonShape.new()
any : A new `b2.PolygonShape` object.
any : A new `b2.PolygonShape` object.

b2 . PolygonShape : set 2011.6+


Copy vertices. This assumes the vertices define a convex polygon. It is assumed that the exterior is the the
right of each edge.
b2.PolygonShape:set(vertices)
vertices : (any) A list of numbers that contains the x, y coordinates of the vertices sequentially

Example:
local polygonShape=b2.PolygonShape.new()
polygonShape:set(1,4, 2,6, 3,7)

b2 . PolygonShape : setAsBox 2011.6+


Build vertices to represent an oriented box.
b2.PolygonShape:setAsBox(hx, hy, centerx, centery, angle)
hx : (num) the half-width
hy : (num) the half-heigh
centerx : (number, default = 0) the x coordinate of the center of the box in local coordinates
centery : (number, default = 0) the y coordinate of the center of the box in local coordinates
angle : (number, default = 0) the rotation of the box in local coordinates

Gideros API Reference v2017.12 Page 151


b2.PrismaticJoint Inherits: b2.Joint 2011.6+
A prismatic joint. This joint provides one degree of freedom: translation along an axis fixed in body1. Relative
rotation is prevented. You can use a joint limit to restrict the range of motion and a joint motor to drive the
motion or to model joint friction.

Prismatic joint
--create empty box2d body for joint
local ground=world:createBody({})
ground:setPosition(465, 480)

--axisx, axisy values usually between 0 and 1


--0 0 moves freely
--0 1 moves on y axis
--1 0 moves on x axis
--1 1 moves on diagonal
local jointDef=b2.createPrismaticJointDef(body, ground, 350, 100, 0.3, 1)
local prismaticJoint=world:createJoint(jointDef)

b2 . PrismaticJoint : enableLimit 2011.6+


Enables or disables the joint limit.
b2.PrismaticJoint:enableLimit(flag)
flag : (bool) enable flag of joint limit

b2 . PrismaticJoint : enableMotor 2011.6+


Enables or disables the joint motor.
b2.PrismaticJoint:enableMotor(flag)
flag : (bool) enable flag of joint motor

b2 . PrismaticJoint : getJointSpeed 2011.6+


Returns the current joint translation speed, usually in meters per second.
num = b2.PrismaticJoint:getJointSpeed()
num : The current joint translation speed, usually in meters per second

b2 . PrismaticJoint : getJointTranslation 2011.6+


Returns the current joint translation, usually in meters.
num = b2.PrismaticJoint:getJointTranslation()
num : The current joint translation, usually in meters

b2 . PrismaticJoint : getLimits 2011.6+


Returns the lower and upper joint limit, usually in meters.
num, num = b2.PrismaticJoint:getLimits()
num : lower joint limit, usually in meters
num : upper joint limit, usually in meters

Gideros API Reference v2017.12 Page 152


b2 . PrismaticJoint : getMotorSpeed 2011.6+
Returns the motor speed in meters per second.
num = b2.PrismaticJoint:getMotorSpeed()
num : The motor speed in meters per second

b2 . PrismaticJoint : isLimitEnabled 2011.6+


Is the joint limit enabled?
bool = b2.PrismaticJoint:isLimitEnabled()
bool : `true` if joint limit is enabled, `false` otherwise

b2 . PrismaticJoint : isMotorEnabled 2011.6+


Is the joint motor enabled?
bool = b2.PrismaticJoint:isMotorEnabled()
bool : `true` if joint motor is enabled, `false` otherwise

b2 . PrismaticJoint : setLimits 2011.6+


Sets the joint limits, usually in meters.
b2.PrismaticJoint:setLimits(lower, upper)
lower : (num) lower joint limit in meters
upper : (num) upper joint limit in meters

b2 . PrismaticJoint : setMaxMotorForce 2011.6+


Sets the maximum motor force, usually in N.
b2.PrismaticJoint:setMaxMotorForce(force)
force : (num) the maximum motor force, usually in N.

b2 . PrismaticJoint : setMotorSpeed 2011.6+


Sets the motor speed in meters per second.
b2.PrismaticJoint:setMotorSpeed(speed)
speed : (num) motor speed in meters per second

b2 . RevoluteJoint : getMotorForce 2011.6+


Returns the current motor force given the inverse time step, usually in N.
num = b2.RevoluteJoint:getMotorForce(inv_dt)

Parameter:
inv_dt : (num)

Result:
num : The current motor force given the inverse time step, usually in N

Gideros API Reference v2017.12 Page 153


b2.PulleyJoint Inherits: b2.Joint 2011.6+
The pulley joint is connected to two bodies and two fixed ground points. The pulley supports a ratio such that:
length1 ratio * length2 <= constant Yes, the force transmitted is scaled by the ratio. The pulley also enforces
a maximum length limit on both sides. This is useful to prevent one side of the pulley hitting the top.

Pulley joint
--create empty box2d body for joint
local ground=world:createBody({})

local jointDef=b2.createPulleyJointDef(body1, body2,


200, 100, --coordinates where "imaginary string" is attached in the air for body 1
350, 100, --coordinates where "imaginary string" is attached in the air for body 2
200, 300, --coordinates where "imaginary string" is attached to the body 1
350, 300, --coordinates where "imaginary string" is attached in the body 2
1) -- ratio (if < 1 -> makes body 2 heavier, > 1 makes body 1 heavier, =1 makes them equal
local pulleyJoint=world:createJoint(jointDef)

b2 . PulleyJoint : getGroundAnchorA 2011.6+


Returns the x and y coordinates of the first ground anchor.
num, num = b2.PulleyJoint:getGroundAnchorA()
num : x coordinates of the first ground anchor
num : y coordinates of the first ground anchor

b2 . PulleyJoint : getGroundAnchorB 2011.6+


Returns the x and y coordinates of the second ground anchor.
num, num = b2.PulleyJoint:getGroundAnchorB()
num : x coordinates of the second ground anchor
num : y coordinates of the second ground anchor

b2 . PulleyJoint : getLengthA 2011.6+


Returns the current length of the segment attached to bodyA.
num = b2.PulleyJoint:getLengthA()
num : The current length of the segment attached to bodyA

b2 . PulleyJoint : getLengthB 2011.6+


Returns the current length of the segment attached to bodyB.
num = b2.PulleyJoint:getLengthB()
num : The current length of the segment attached to bodyB

b2 . PulleyJoint : getRatio 2011.6+


Returns the pulley ratio.
num = b2.PulleyJoint:getRatio()
num : The pulley ratio

Gideros API Reference v2017.12 Page 154


b2.RevoluteJoint Inherits: b2.Joint 2011.6+
A revolute joint constrains two bodies to share a common point while they are free to rotate about the point.
The relative rotation about the shared point is the joint angle. You can limit the relative rotation with a joint
limit that specifies a lower and upper angle. You can use a motor to drive the relative rotation about the
shared point. A maximum motor torque is provided so that infinite forces are not generated.

Revolute joint
--create empty box2d body for joint
local ground=world:createBody({})
ground:setPosition(300, 480)

local jointDef=b2.createRevoluteJointDef(body, ground, 300, 300)


local revoluteJoint=world:createJoint(jointDef)
--will not let ball spin for ever
revoluteJoint:setMaxMotorTorque(1)
revoluteJoint:enableMotor(true)

b2 . RevoluteJoint : enableLimit 2011.6+


Enables or disables the joint limit.
b2.RevoluteJoint:enableLimit(flag)
flag : (bool) enable flag of joint limit

b2 . RevoluteJoint : enableMotor 2011.6+


Enables or disables the joint motor.
b2.RevoluteJoint:enableMotor(flag)
flag : (bool) enable flag of joint motor

b2 . RevoluteJoint : getJointAngle 2011.6+


Returns the current joint angle in radians.
num = b2.RevoluteJoint:getJointAngle()
num : The current joint angle in radians

b2 . RevoluteJoint : getJointSpeed 2011.6+


Returns the current joint angle speed in radians per second.
num = b2.RevoluteJoint:getJointSpeed()
num : The current joint angle speed in radians per second

b2 . RevoluteJoint : getLimits 2011.6+


Returns the lower and upper joint limit in radians.
num, num = b2.RevoluteJoint:getLimits()
num : lower joint limit in radians
num : upper joint limit in radians

Gideros API Reference v2017.12 Page 155


b2 . RevoluteJoint : getMotorSpeed 2011.6+
Returns the motor speed in radians per second.
num = b2.RevoluteJoint:getMotorSpeed()
num : The motor speed in radians per second

b2 . RevoluteJoint : getMotorTorque 2011.6+


Returns the current motor torque given the inverse time step. Unit is N*m.
num = b2.RevoluteJoint:getMotorTorque(inv_dt)

Parameter:
inv_dt : (num)

Result:
num : The current motor torque given the inverse time step. Unit is N*m

b2 . RevoluteJoint : isLimitEnabled 2011.6+


Is the joint limit enabled?
bool = b2.RevoluteJoint:isLimitEnabled()
bool : `true` if joint limit is enabled, `false` otherwise

b2 . RevoluteJoint : isMotorEnabled 2011.6+


Is the joint motor enabled?
bool = b2.RevoluteJoint:isMotorEnabled()
bool : `true` if joint motor is enabled, `false` otherwise

b2 . RevoluteJoint : setLimits 2011.6+


Sets the joint limits in radians.
b2.RevoluteJoint:setLimits(lower, upper)
lower : (num) lower joint limit in radians
upper : (num) upper joint limit in radians

b2 . RevoluteJoint : setMaxMotorTorque 2011.6+


Sets the maximum motor torque, usually in N-m.
b2.RevoluteJoint:setMaxMotorTorque(torque)
torque : (num) the maximum motor torque, usually in N-m

b2 . RevoluteJoint : setMotorSpeed 2011.6+


Sets the motor speed in radians per second.
b2.RevoluteJoint:setMotorSpeed(speed)
speed : (num) motor speed in radians per second

Gideros API Reference v2017.12 Page 156


b2.RopeJoint Inherits: b2.Joint 2011.6+
A rope joint enforces a maximum distance between two points on two bodies. It has no other effect.Warning:
if you attempt to change the maximum length during the simulation you will get some non-physical
behavior.A model that would allow you to dynamically modify the length would have some sponginess, so I
chose not to implement it that way.See `b2.DistanceJoint` if you want to dynamically control length.

b2 . RopeJoint : getMaxLength 2012.09.3+


Returns the maximum length of the rope.
num = b2.RopeJoint:getMaxLength()
num : The maximum length of the rope.

b2 . RopeJoint : setMaxLength 2012.09.3+


Sets the maximum length of the rope.
b2.RopeJoint:setMaxLength(maxLength)
maxLength : (num)

Gideros API Reference v2017.12 Page 157


b2.Shape 2011.6+
A shape is used for collision detection.You can not create a `b2.Shape` instance directly, but instead you
create `b2.CircleShape`, `b2.ChainShape` and `b2.PolygonShape` instances.

Gideros API Reference v2017.12 Page 158


b2.WeldJoint Inherits: b2.Joint 2011.6+
A weld joint essentially glues two bodies together. A weld joint may distort somewhat because the island
constraint solver is approximate.

Weld joint
local jointDef=b2.createWeldJointDef(body1, body2, 100, 100, 130, 100)
local weldJoint=world:createJoint(jointDef)

b2 . WeldJoint : getDampingRatio 2011.6+


Returns damping ratio.
num = b2.WeldJoint:getDampingRatio()
num : Damping ratio

b2 . WeldJoint : getFrequency 2011.6+


Returns frequency in Hz.
num = b2.WeldJoint:getFrequency()
num : Frequency in Hz

b2 . WeldJoint : setDampingRatio 2011.6+


Sets damping ratio.
b2.WeldJoint:setDampingRatio(damping)
damping : (num) damping ratio

b2 . WeldJoint : setFrequency 2011.6+


Sets frequency in Hz.
b2.WeldJoint:setFrequency(frequency)
frequency : (num) frequency in Hz

Gideros API Reference v2017.12 Page 159


b2.WheelJoint Inherits: b2.Joint 2011.6+
A wheel joint provides two degrees of freedom: translation along an axis fixed in bodyA and rotation in the
plane. You can use a joint limit to restrict the range of motion and a joint motor to drive the rotation or to
model rotational friction. This joint is designed for vehicle suspensions.

Wheel joint
--create empty box2d body for joint
local ground=world:createBody({})
ground:setPosition(350, 480)

--axisx, axisy values usually between 0 and 1


--0 0 moves freely
--0 1 force pulling back on y axis
--1 0 force pulling back on x axis
--1 1 force pulling back all diretions
local jointDef=b2.createWheelJointDef(body, ground, 350, 200, 1, 1)
local wheelJoint=world:createJoint(jointDef)

b2 . WheelJoint : enableMotor 2011.6+


Enables or disables the joint motor.
b2.WheelJoint:enableMotor(flag)
flag : (bool) enable flag of joint motor

b2 . WheelJoint : getJointSpeed 2011.6+


Returns the current joint translation speed in meters per second.
num = b2.WheelJoint:getJointSpeed()
num : The current joint translation speed in meters per second

b2 . WheelJoint : getJointTranslation 2011.6+


Returns the current joint translation in meters.
num = b2.WheelJoint:getJointTranslation()
num : The current joint translation in meters

b2 . WheelJoint : getMaxMotorTorque 2011.6+


Returns the maximum motor torque in N*m.
num = b2.WheelJoint:getMaxMotorTorque()
num : The maximum motor torque in N-m

b2 . WheelJoint : getMotorSpeed 2011.6+


Returns the motor speed in radians per second.
num = b2.WheelJoint:getMotorSpeed()
num : The motor speed in radians per second

Gideros API Reference v2017.12 Page 160


b2 . WheelJoint : getSpringDampingRatio 2011.6+
Returns the spring damping ratio.
num = b2.WheelJoint:getSpringDampingRatio()
num : The spring damping ratio

b2 . WheelJoint : getSpringFrequencyHz 2011.6+


Returns the spring frequency in hertz.
num = b2.WheelJoint:getSpringFrequencyHz()
num : The spring frequency in hertz.

b2 . WheelJoint : isMotorEnabled 2011.6+


Is the joint motor enabled?
bool = b2.WheelJoint:isMotorEnabled()
bool : `true` if joint motor is enabled, `false` otherwise

b2 . WheelJoint : setMaxMotorTorque 2011.6+


Sets the maximum motor torque in N*m.
b2.WheelJoint:setMaxMotorTorque(torque)
torque : (num) the maximum motor torque in N-m

b2 . WheelJoint : setMotorSpeed 2011.6+


Sets the motor speed in radians per second.
b2.WheelJoint:setMotorSpeed(speed)
speed : (num) motor speed in radians per second

b2 . WheelJoint : setSpringDampingRatio 2011.6+


Sets the spring damping ratio.
b2.WheelJoint:setSpringDampingRatio(damping)
damping : (num) damping ratio

b2 . WheelJoint : setSpringFrequencyHz 2011.6+


Sets the spring frequency in hertz. Setting the frequency to zero disables the spring.
b2.WheelJoint:setSpringFrequencyHz(frequency)
frequency : (num) spring frequency in hertz

Gideros API Reference v2017.12 Page 161


b2.World Inherits: EventDispatcher 2011.6+
The `b2.World` class inherits from the following class: `EventDispatcher`.The `b2.World` class manages all
physics entities and dynamic simulation. It is possible to create and manage more than one `b2.World`
instance.

Creating Box2d body and moving Bitmap along the body


require "box2d"
local world=b2.World.new(0, 10, true)

--create ball bitmap object from ball graphic


local ball=Bitmap.new(Texture.new("ball.png"))
--reference center of the ball for positioning
ball:setAnchorPoint(0.5,0.5)

ball:setPosition(100,100)

--get radius
local radius=ball:getWidth()/2

--create box2d physical object


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

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

Detecting collisions between bodies


--add collision event listener
world:addEventListener(Event.BEGIN_CONTACT, function(e)
--getting contact bodies
local fixtureA=e.fixtureA
local fixtureB=e.fixtureB
local bodyA=fixtureA:getBody()
local bodyB=fixtureB:getBody()

--do what you need with colliding bodies


end)

--add collision event listener


world:addEventListener(Event.END_CONTACT, function(e)
--getting contact bodies
local fixtureA=e.fixtureA

Gideros API Reference v2017.12 Page 162


local fixtureB=e.fixtureB
local bodyA=fixtureA:getBody()
local bodyB=fixtureB:getBody()

--do what you need with colliding bodies


end)

--add collision event listener


world:addEventListener(Event.PRE_SOLVE, function(e)
--getting contact bodies
local fixtureA=e.fixtureA
local fixtureB=e.fixtureB
local bodyA=fixtureA:getBody()
local bodyB=fixtureB:getBody()

--do what you need with colliding bodies


end)

--add collision event listener


world:addEventListener(Event.POST_SOLVE, function(e)
--getting contact bodies
local fixtureA=e.fixtureA
local fixtureB=e.fixtureB
local bodyA=fixtureA:getBody()
local bodyB=fixtureB:getBody()

--do what you need with colliding bodies

--additionally get collision force


print(event.maxImpulse)
end)

b2 . World . new 2011.6+


Creates a new `b2.World` object. You can create more then one `b2.World` object to manage independent
worlds.
any, any = b2.World.new(gravityx, gravityy, doSleep)

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.

b2 . World : clearForces 2011.6+


Call this after you are done with time steps to clear the forces. You normally call this after each call to
`b2.World:step`,unless you are performing sub-steps. By default, forces will be automatically cleared, so you
don't need to call this function.
b2.World:clearForces()

Gideros API Reference v2017.12 Page 163


b2 . World : createBody 2011.6+
Creates a rigid body given a definition. The body definition is given as an ordinary table. The fields of the
body definition table are:<ul><li>**type**: (number) The body type: `b2.STATIC_BODY`,
`b2.KINEMATIC_BODY`, or `b2.DYNAMIC_BODY`. Note: if a dynamic body would have zero mass, the
mass is set to one.</li><li>**position**: (table) The world position of the body (see the example below to
understand how this table is set). Avoid creating bodies at the origin since this can lead to many overlapping
shapes.</li><li>**angle**: (number) The world angle of the body in radians.</li><li>**linearVelocity**: (table)
The linear velocity of the body's origin in world co-ordinates (see the example below to understand how this
table is set).</li><li>**angularVelocity**: (number) The angular velocity of the
body.</li><li>**linearDamping**: (number) Linear damping is use to reduce the linear velocity. The damping
parameter can be larger than 1.0 but the damping effect becomes sensitive to the time step when the
damping parameter is large.</li><li>**angularDamping**: (number) Angular damping is use to reduce the
angular velocity. The damping parameter can be larger than 1.0 but the damping effect becomes sensitive to
the time step when the damping parameter is large.</li><li>**allowSleep**: (boolean) Set this flag to false if
this body should never fall asleep. Note that this increases CPU usage.</li><li>**awake**: (boolean) Is this
body initially awake or sleeping?</li><li>**fixedRotation**: (boolean) Should this body be prevented from
rotating? Useful for characters.</li><li>**bullet**: (boolean) Is this a fast moving body that should be
prevented from tunneling through other moving bodies? Note that all bodies are prevented from tunneling
through kinematic and static bodies. This setting is only considered on dynamic bodies. **Warning:** You
should use this flag sparingly since it increases processing time.</li><li>**active**: (boolean) Does this body
start out active?</li><li>**gravityScale**: (number) Scale the gravity applied to this body.</li></ul>The
unset fields gets default values.<ul><li>*Warning:** This function is locked during callbacks.</li></ul>
b2.Body = b2.World:createBody(bodyDef)

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},
}

b2 . World : createJoint 2011.6+


Creates a joint given a definition. All 10 types of joints is created by using this function:<h3>Revolute
Joint</h3>Revolute joint definition. This requires defining an anchor point where the bodies are joined. The
definition useslocal anchor points so that the initial configuration can violate the constraint slightly. You also
need to specify theinitial relative angle for joint limits. This helps when saving and loading a game. The local
anchor points are measured fromthe body's origin rather than the center of mass because:1. you might not
know where the center of mass will be.2. if you add/remove shapes from a bodyand recompute the mass,
the joints will be broken.<ul><li>**type**: (number) b2.REVOLUTE_JOINT</li><li>**bodyA**: (b2.Body)
The first attached body.</li><li>**bodyB**: (b2.Body) The second attached
body.</li><li>**collideConnected**: (boolean) Set this flag to true if the attached bodies should
collide.</li><li>**localAnchorA**: (table) The local anchor point relative to bodyA's
origin.</li><li>**localAnchorB**: (table) The local anchor point relative to bodyB's
origin.</li><li>**referenceAngle**: (number) The bodyB angle minus bodyA angle in the reference state
(radians).</li><li>**enableLimit**: (boolean) A flag to enable joint limits.</li><li>**lowerAngle**: (number)

Gideros API Reference v2017.12 Page 164


The lower angle for the joint limit (radians).</li><li>**upperAngle**: (number) The upper angle for the joint
limit (radians).</li><li>**enableMotor**: (boolean) A flag to enable the joint motor.</li><li>**motorSpeed**:
(number) The desired motor speed. Usually in radians per second.</li><li>**maxMotorTorque**: (number)
The maximum motor torque used to achieve the desired motor speed. Usually in N-m.</li></ul>Also, you
can use [[b2.createRevoluteJointDef]] function to create a revolute joint definiton table easier.<h3>Prismatic
Joint</h3>Prismatic joint definition. This requires defining a line of motion using an axis and an anchor point.
The definition useslocal anchor points and a local axis so that the initial configuration can violate the
constraint slightly. The joint translation iszero when the local anchor points coincide in world space. Using
local anchors and a local axis helps when saving and loading a game.<ul><li>**type**: (number)
b2.PRISMATIC_JOINT</li><li>**bodyA**: (b2.Body) The first attached body.</li><li>**bodyB**: (b2.Body)
The second attached body.</li><li>**collideConnected**: (boolean) Set this flag to true if the attached bodies
should collide.</li><li>**localAnchorA**: (table) The local anchor point relative to bodyA's
origin.</li><li>**localAnchorB**: (table) The local anchor point relative to bodyB's
origin.</li><li>**localAxisA**: (table) The local translation axis in bodyA.</li><li>**referenceAngle**:
(number) The body2 angle minus body1 angle in the reference state (radians).</li><li>**enableLimit**:
(boolean) A flag to enable joint limits.</li><li>**lowerTranslation**: (number) The lower translation limit,
usually in meters.</li><li>**upperTranslation**: (number) The upper translation limit, usually in
meters.</li><li>**enableMotor**: (boolean) A flag to enable the joint motor.</li><li>**maxMotorForce**:
(number) The maximum motor torque, usually in N-m.</li><li>**motorSpeed**: (number) The desired motor
speed in radians per second.</li></ul>Also, you can use [[b2.createPrismaticJointDef]] function to create a
prismatic joint definiton table easier.<h3>Distance Joint</h3>Distance joint definition. This requires
defining an anchor point on both bodies and the non-zero length of the distance joint.The definition uses
local anchor points so that the initial configuration can violate the constraint slightly.This helps when saving
and loading a game.<ul><li>**type**: (number) b2.DISTANCE_JOINT</li><li>**bodyA**: (b2.Body) The
first attached body.</li><li>**bodyB**: (b2.Body) The second attached body.</li><li>**collideConnected**:
(boolean) Set this flag to true if the attached bodies should collide.</li><li>**localAnchorA**: (table) The local
anchor point relative to bodyA's origin.</li><li>**localAnchorB**: (table) The local anchor point relative to
bodyB's origin.</li><li>**length**: (number) The natural length between the anchor points. Do not use a zero
or short length.</li><li>**frequencyHz**: (number) The mass-spring-damper frequency in
Hertz.</li><li>**dampingRatio**: (number) The damping ratio. 0 = no damping, 1 = critical
damping.</li></ul>Also, you can use [[b2.createDistanceJointDef]] function to create a distance joint
definiton table easier.<h3>Pulley Joint</h3>Pulley joint definition. This requires two ground anchors, two
dynamic body anchor points, max lengths for each side, and a pulley ratio.<ul><li>**type**: (number)
b2.PULLEY_JOINT</li><li>**bodyA**: (b2.Body) The first attached body.</li><li>**bodyB**: (b2.Body) The
second attached body.</li><li>**collideConnected**: (boolean) Set this flag to true if the attached bodies
should collide.</li><li>**groundAnchorA**: (table) The first ground anchor in world coordinates. This point
never moves.</li><li>**groundAnchorB**: (table) The second ground anchor in world coordinates. This point
never moves.</li><li>**localAnchorA**: (table) The local anchor point relative to bodyA's
origin.</li><li>**localAnchorB**: (table) The local anchor point relative to bodyB's origin.</li><li>**lengthA**:
(number) The a reference length for the segment attached to bodyA.</li><li>**lengthB**: (number) The a
reference length for the segment attached to bodyB.</li><li>**ratio**: (number) The pulley ratio, used to
simulate a block-and-tackle.</li></ul>Also, you can use [[b2.createPulleyJointDef]] function to create a
pulley joint definiton table easier.<h3>Mouse Joint</h3>Mouse joint definition. This requires a world target
point, tuning parameters, and the time step.<ul><li>**type**: (number)
b2.MOUSE_JOINT</li><li>**bodyA**: (b2.Body) The first attached body.</li><li>**bodyB**: (b2.Body) The
second attached body.</li><li>**collideConnected**: (boolean) Set this flag to true if the attached bodies
should collide.</li><li>**target**: (table) The initial world target point. This is assumed to coincide with the
body anchor initially.</li><li>**maxForce**: (number) The maximum constraint force that can be exerted to
move the candidate body. Usually you will express as some multiple of the weight (multiplier * mass *
gravity).</li><li>**frequencyHz**: (number) The response speed.</li><li>**dampingRatio**: (number) The
damping ratio. 0 = no damping, 1 = critical damping.</li></ul>Also, you can use [[b2.createMouseJointDef]]
function to create a mouse joint definiton table easier.<h3>Gear Joint</h3>Gear joint definition. This
definition requires two existing revolute or prismatic joints (any combination will work). The provided

Gideros API Reference v2017.12 Page 165


jointsmust attach a dynamic body to a static body.<ul><li>**type**: (number)
b2.GEAR_JOINT</li><li>**bodyA**: (b2.Body) The first attached body.</li><li>**bodyB**: (b2.Body) The
second attached body.</li><li>**collideConnected**: (boolean) Set this flag to true if the attached bodies
should collide.</li><li>**joint1**: (b2.Joint) The first revolute/prismatic joint attached to the gear
joint.</li><li>**joint2**: (b2.Joint) The second revolute/prismatic joint attached to the gear
joint.</li><li>**ratio**: (number) The gear ratio.</li></ul>Also, you can use [[b2.createGearJointDef]]
function to create a gear joint definiton table easier.<h3>Wheel Joint</h3>Wheel joint definition. This
requires defining a line of motion using an axis and an anchor point. The definition uses local anchor points
and a local axis so that the initial configuration can violate the constraint slightly. The joint translation is zero
when the local anchor points coincide in world space. Using local anchors and a local axis helps when
saving and loading a game.<ul><li>**type**: (number) b2.WHEEL_JOINT</li><li>**bodyA**: (b2.Body) The
first attached body.</li><li>**bodyB**: (b2.Body) The second attached body.</li><li>**collideConnected**:
(boolean) Set this flag to true if the attached bodies should collide.</li><li>**localAnchorA**: (table) The local
anchor point relative to bodyA's origin.</li><li>**localAnchorB**: (table) The local anchor point relative to
bodyB's origin.</li><li>**localAxisA**: (table) The local translation axis in bodyA.</li><li>**enableMotor**:
(boolean) A flag to enable the joint motor.</li><li>**maxMotorTorque**: (number) The maximum motor
torque, usually in N-m.</li><li>**motorSpeed**: (number) The desired motor speed in radians per
second.</li><li>**frequencyHz**: (number) Suspension frequency, zero indicates no
suspension.</li><li>**dampingRatio**: (number) Suspension damping ratio, one indicates critical
damping.</li></ul>Also, you can use [[b2.createWheelJointDef]] function to create a wheel joint definiton
table easier.<h3>Weld Joint</h3>Weld joint definition. You need to specify local anchor points where they
are attached and the relativebody angle. The position of the anchor points is important for computing the
reaction torque.<ul><li>**type**: (number) b2.WELD_JOINT</li><li>**bodyA**: (b2.Body) The first
attached body.</li><li>**bodyB**: (b2.Body) The second attached body.</li><li>**collideConnected**:
(boolean) Set this flag to true if the attached bodies should collide.</li><li>**localAnchorA**: (table) The local
anchor point relative to bodyA's origin.</li><li>**localAnchorB**: (table) The local anchor point relative to
bodyB's origin.</li><li>**referenceAngle**: (number) The bodyB angle minus bodyA angle in the reference
state (radians).</li></ul>Also, you can use [[b2.createWeldJointDef]] function to create a weld joint definiton
table easier.<h3>Friction Joint</h3>Friction joint definition.<ul><li>**type**: (number)
b2.LINE_JOINT</li><li>**bodyA**: (b2.Body) The first attached body.</li><li>**bodyB**: (b2.Body) The
second attached body.</li><li>**collideConnected**: (boolean) Set this flag to true if the attached bodies
should collide.</li><li>**localAnchorA**: (table) The local anchor point relative to bodyA's
origin.</li><li>**localAnchorB**: (table) The local anchor point relative to bodyB's
origin.</li><li>**maxForce**: (number) The maximum friction force in N.</li><li>**maxTorque**: (number)
The maximum friction torque in N-m.</li></ul><h3>Rope Joint</h3>Rope joint definition. This requires
two body anchor points and a maximum length.<ul><li>**type**: (number)
b2.ROPE_JOINT</li><li>**bodyA**: (b2.Body) The first attached body.</li><li>**bodyB**: (b2.Body) The
second attached body.</li><li>**collideConnected**: (boolean) Set this flag to true if the attached bodies
should collide.</li><li>**localAnchorA**: (table) The local anchor point relative to bodyA's
origin.</li><li>**localAnchorB**: (table) The local anchor point relative to bodyB's
origin.</li><li>**maxLength**: (number) The maximum length of the rope.</li></ul>Also, you can use
[[b2.createRopeJointDef]] function to create a rope joint definiton table easier.
b2.Joint = b2.World:createJoint(jointDef)

Parameter:
jointDef : (table)

Result:
b2.Joint : created joint

b2 . World : createParticleSystem 2015.06.30+


Creats new particle system, which will use Liquid fun.Parameters that you can provide in

Gideros API Reference v2017.12 Page 166


table:"pressureStrength", "dampingStrength", "elaticStrength", "springStrength", "viscousStrength",
"surfaceTensionPressureStrength", "surfaceTensionNormalStrength", "repulsiveStrength", "powderStrength",
"ejectionStrength", "staticPressureStrength", "staticPressureRelaxation", "colorMixingStrength",
"lifetimeGranularity","radius","staticPressureIterations","destroyByAge"
b2.ParticleSystem = b2.World:createParticleSystem(particleSysDef)

Parameter:
particleSysDef : (table) parameters that define particle system

Result:
b2.ParticleSystem : new particle system

b2 . World : destroyBody 2011.6+


Destroys a rigid body. This function is locked during callbacks.<ul><li>*Warning:**</li></ul><ul><li>This
automatically deletes all associated shapes and joints.</li><li>This function is locked during
callbacks.</li></ul>
b2.World:destroyBody(body)
body : (b2.Body) body to be destroyed

b2 . World : destroyJoint 2011.6+


Destroy a joint. This may cause the connected bodies to begin colliding. <ul><li>*Warning:** This function
is locked during callbacks.</li></ul>
b2.World:destroyJoint(joint)
joint : (b2.Joint) joint to be destroyed

b2 . World : getGravity 2011.6+


Returns the gravity vector.
num, num = b2.World:getGravity()
num : x component of gravity vector.
num : y component of gravity vector.

b2 . World : queryAABB 2011.6+


Query the world for all fixtures that potentially overlap the provided AABB.
table = b2.World:queryAABB(minx, miny, maxx, maxy)

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

Query specific area for bodies


--get all fixtures in this area
local fixtures=world:queryAABB(0, 0, 100, 10)
--check if there are any fixture
if #fixtures > 0 then

Gideros API Reference v2017.12 Page 167


for i=1, #fixtures do
--getting body of fixture
local body=fixtures[i]:getBody()
end
end

b2 . World : rayCast 2011.6+


Ray-cast the world for all fixtures in the path of the ray. Your callback controls whether you get the closest
point, any point, or n-points. The ray-cast ignores shapes that contain the starting point. Listener function is
called for each fixture found in the query and accepts 6 parameters (7 if data parameter is provided):1. the
fixture hit by the ray2. the x coordinate of the point of initial intersection 3. the y coordinate of the point of
initial intersection4. the x coordinate of the normal vector at the point of intersection 5. the y coordinate of
the normal vector at the point of intersection 6. fractionYou control how the ray cast proceeds by returning a
number:<ul><li>return no value or -1: ignore this fixture and continue</li><li>return 0: terminate the ray
cast</li><li>return fraction: clip the ray to this point</li><li>return 1: don't clip the ray and continue</li></ul>
b2.World:rayCast(x1, y1, x2, y2, listener [, data])
x1 : (num) the x coordinate of the ray starting point
y1 : (num) the y coordinate of the ray starting point
x2 : (num) the x coordinate of the ray ending point
y2 : (num) the y coordinate of the ray ending point
listener : (function) the listener function that processes the results
data : (any) an optional data parameter that is passed as a first argument to the listener function

Detecting bodies with raycasting


local raycastCallback function(fixture, hitX, hitY, vectX, vectY, fration)
--so if this function is called, it means we hit some kind of object
--and it's fixture is stored in first variable we named "fixture"
--so we can for example get body
local body=fixture:getBody()

end

--now we add callback function for projected raycast above body


--Parameters:
--object x coordinate
--object y coordinate
--projection vector on x axis
--projection vector on y axis
--callback function
local x, y=body:getPosition()
world:rayCast(x, y, x, y-100, raycastCallback)

b2 . World : setDebugDraw 2011.6+


Registers a b2.DebugDraw instance for debug drawing.
b2.World:setDebugDraw()

Example:
local debugDraw=b2.DebugDraw.new()
world:setDebugDraw(debugDraw)
stage:addChild(debugDraw)

Gideros API Reference v2017.12 Page 168


b2 . World : setGravity 2011.6+
Sets the gravity vector.
b2.World:setGravity(gravityx, gravityy)
gravityx : (num) the x component the gravity
gravityy : (num) the y component the gravity

b2 . World : step 2011.6+


Take a time step. This performs collision detection, integration, and constraint solution.
b2.World:step(timeStep, velocityIterations, positionIterations)
timeStep : (num) the amount of time to simulate, this should not vary
velocityIterations : (num) for the velocity constraint solver
positionIterations : (num) for the position constraint solver

Creating Box2d body and moving Bitmap along the body


require "box2d"
local world=b2.World.new(0, 10, true)

--create ball bitmap object from ball graphic


local ball=Bitmap.new(Texture.new("ball.png"))
--reference center of the ball for positioning
ball:setAnchorPoint(0.5,0.5)

ball:setPosition(100,100)

--get radius
local radius=ball:getWidth()/2

--create box2d physical object


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

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

Gideros API Reference v2017.12 Page 169


b2.WorldManifold 2012.09.6+
Contains information about contact relative to the world

Checking collisions from bottom using b2.Contact


local isTouchingGround=false
world:addEventListener(Event.BEGIN_CONTACT, function(e)
local manifold=e.contact:getWorldManifold()
if manifold.normal.y > 0.9 then
--collision came from bottom
isTouchingGround=true
end
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)

Example content of b2.WorldManifold


[normal] => Table {
{
[y] => -1
[x] => 0
}
[points] => Table {
{
[1] => Table {
{
[y] => 319.92502212524
[x] => 99.999997615814
}
}

Gideros API Reference v2017.12 Page 170


Lua API
This is a decription of the main Lua API.

Gideros API Reference v2017.12 Page 171


(global) 2011.6+
Global scope of Lua environment

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.

Gideros API Reference v2017.12 Page 172


table = getfenv([f])

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

Gideros API Reference v2017.12 Page 173


chunkname : (str) is used as the chunk name for error messages and debug information.

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+

Gideros API Reference v2017.12 Page 174


Receives any number of arguments, and prints their values to `stdout`, using the `tostring` function to convert
them to strings. print is not intended for formatted output, but only as a quick way to show a value, typically
for debugging. For formatted output, use `string.format`.
print(e1 [, e2] [, ...])
e1 : (any) any argument
e2 : (any) any second argument
... : (any) other optional arguments

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

Gideros API Reference v2017.12 Page 175


setfenv 2011.6+
Sets the environment to be used by the given function. f can be a Lua function or a number that specifies the
function at that stack level: Level 1 is the function calling setfenv. setfenv returns the given function. As a
special case, when f is 0 setfenv changes the environment of the running thread. In this case, setfenv returns
no values.
varies = setfenv(f, table)

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

Gideros API Reference v2017.12 Page 176


Result:
str : value converted to string or nil

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

Gideros API Reference v2017.12 Page 177


coroutine 2011.6+
Suspends the execution of the calling coroutine. The coroutine cannot be running a C function, a
metamethod, or an iterator. Any arguments to yield are passed as extra results to resume.

Simple coroutine usage example


--To create a coroutine we must have function which represents it, e.g.,
function foo()
print("foo", 1)
coroutine.yield()
print("foo", 2)
end

--[[ 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: ]]

co=coroutine.create(foo) -- create a coroutine with foo as the entry


print(type(co)) -- display the type of object "co"=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

-- Once a coroutine exits or returns like a function it cannot be resumed.

coroutine . create 2011.6+


Creates a new coroutine, with body f. f must be a Lua function. Returns this new coroutine, an object with
type "thread".
coroutine = coroutine.create(f)

Parameter:
f : (function) lua function

Gideros API Reference v2017.12 Page 178


Result:
coroutine : created coroutine

coroutine . resume 2011.6+


Starts or continues the execution of coroutine co. The first time you resume a coroutine, it starts running its
body. The values val1, ··· are passed as the arguments to the body function. If the coroutine has yielded,
resume restarts it; the values val1, ··· are passed as the results from the yield. If the coroutine runs without
any errors, resume returns true plus any values passed to yield (if the coroutine yields) or any values
returned by the body function (if the coroutine terminates). If there is any error, resume returns false plus the
error message.
bool, multiple = coroutine.resume(co [, val1] [, ...])

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

coroutine . status 2011.6+


Returns the status of `coroutine` co, as a string: "running", if the coroutine is running (that is, it called status);
"suspended", if the coroutine is suspended in a call to yield, or if it has not started running yet; "normal" if the
coroutine is active but not running (that is, it has resumed another coroutine); and "dead" if the coroutine has
finished its body function, or if it has stopped with an error.
str = coroutine.status(co)

Parameter:
co : (coroutine) coroutine to check status for

Result:
str : the state of coroutine

coroutine . wrap 2011.6+


Creates a new coroutine, with body f. f must be a Lua function. Returns a function that resumes the coroutine
each time it is called. Any arguments passed to the function behave as the extra arguments to resume.
Returns the same values returned by resume, except the first boolean. In case of error, propagates the error.
function = coroutine.wrap(f)

Parameter:
f : (function) lua function

Result:
function : function that resumes coroutine every time it is called, behaving similar to coroutine.resume

coroutine . yield 2011.6+


In order for multiple coroutines to share execution they must stop executing (after performing a sensible
amount of processing) and pass control to another thread. This act of submission is called yielding.
Coroutines explicitly call a Lua function coroutine.yield(), which is similar to using return in functions. What

Gideros API Reference v2017.12 Page 179


differentiates yielding from function returns is that at a later point we can reenter the thread and carry on
where we left off. When you exit a function scope using return the scope is destroyed and we cannot reenter
it, e.g.,
coroutine.yield([val1] [, ...])
val1 : (any) value to return from coroutine.resume call
... : (multiple) other optional values that will be returned from coroutine.resume call

Gideros API Reference v2017.12 Page 180


debug 2011.6+
The debug library does not give you a debugger for Lua, but it offers all the primitives that you need for
writing a debugger for Lua. For performance reasons, the official interface to these primitives is through the C
API. The debug library in Lua is a way to access these functions directly within Lua code. This library
declares all its functions inside the debug table.

debug . debug 2011.6+


Enters an interactive mode with the user, running each string that the user enters. Using simple commands
and other debug facilities, the user can inspect global and local variables, change their values, evaluate
expressions, and so on. A line containing only the word cont finishes this function, so that the caller continues
its execution. Note that commands for debug.debug are not lexically nested within any function, and so have
no direct access to local variables.
debug.debug()

debug . gethook 2011.6+


Returns the current hook settings of the thread, as three values: the current hook function, the current hook
mask, and the current hook count (as set by the `debug.sethook` function).
function, str, num = debug.gethook()
function : function that works as hook
str : provided mask of the hook
num : hook count

debug . getinfo 2011.6+


Returns a table with information about a function. You can give the function directly, or you can give a
number as the value of function, which means the function running at level function of the call stack of the
given thread: level 0 is the current function (getinfo itself); level 1 is the function that called getinfo; and so on.
If function is a number larger than the number of active functions, then getinfo returns nil. The returned table
can contain all the fields returned by lua_getinfo, with the string what describing which fields to fill in. The
default for what is to get all information available, except the table of valid lines. If present, the option 'f' adds
a field named func with the function itself. If present, the option 'L' adds a field named activelines with the
table of valid lines. For instance, the expression debug.getinfo(1,"n").name returns a table with a name for
the current function, if a reasonable name can be found, and the expression debug.getinfo(print) returns a
table with all available information about the print function.
table = debug.getinfo(function [, what])

Parameters:
function : (any) function or call stack level
what : (str) what information to return

Result:
table : table with information about the function

debug . getlocal 2011.6+


This function returns the name and the value of the local variable with index local of the function at level level
of the stack. (The first parameter or local variable has index 1, and so on, until the last active local variable.)
The function returns nil if there is no local variable with the given index, and raises an error when called with
a level out of range. (You can call debug.getinfo to check whether the level is valid.) Variable names starting

Gideros API Reference v2017.12 Page 181


with '(' (open parentheses) represent internal variables (loop control variables, temporaries, and C function
locals).
str, varies = debug.getlocal(level, local)

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

debug . getupvalue 2011.6+


This function returns the name and the value of the upvalue with index up of the function func. The function
returns nil if there is no upvalue with the given index.
str, varies = debug.getupvalue(func, up)

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

debug . sethook 2011.6+


Sets the given function as a hook. The string mask and the number count describe when the hook will be
called. The string mask may have the following characters, with the given meaning: "c": the hook is called
every time Lua calls a function;"r": the hook is called every time Lua returns from a function;"l": the hook is
called every time Lua enters a new line of code. With a count different from zero, the hook is called after
every count instructions. When called without arguments, debug.sethook turns off the hook. When the hook
is called, its first parameter is a string describing the event that has triggered its call: "call", "return" (or "tail
return", when simulating a return from a tail call), "line", and "count". For line events, the hook also gets the
new line number as its second parameter. Inside a hook, you can call getinfo with level 2 to get more
information about the running function (level 0 is the getinfo function, and level 1 is the hook function), unless
the event is "tail return". In this case, Lua is only simulating the return, and a call to getinfo will return invalid
data.
debug.sethook(hook, mask [, count])
hook : (function) function to be executed as hook
mask : (str) mask of the hook "c", "r" or "l"
count : (num) hook count

debug . setlocal 2011.6+


This function assigns the value value to the local variable with index local of the function at level level of the
stack. The function returns nil if there is no local variable with the given index, and raises an error when
called with a level out of range. (You can call getinfo to check whether the level is valid.) Otherwise, it returns
the name of the local variable.
str = debug.setlocal(level, local, value)

Parameters:
level : (num) level of the stack

Gideros API Reference v2017.12 Page 182


local : (num) index of the variable
value : (varies) value of the variable to set

Result:
str : name of the variable or nil

debug . settypemt 2016.08+


Set meta table typeFrom http://lua-users.org/wiki/LuaPowerPatchesUseful to extend Lua syntax and for some
tricks.Adds new method to debug library:debug.settypemt(type, metatable)Supported types:
"nil","boolean","lightuserdata","number","string","table","function","userdata","thread".For
example:<pre><code>-- enable string indexing (s[n]) to get character at utf8 positionstring.__index =
function(s, n) return utf8.sub(s, n, n) enddebug.settypemt("string", string)local s = "Hello, world!"print(s[8]) -->
w</code></pre>Also sets table library as default type metatable for all tables without user defined metatables
i.e. enables following syntax: t:insert(3); t:remove(2); t:sort(func); etc.
debug.settypemt()

debug . setupvalue 2011.6+


This function assigns the value value to the upvalue with index up of the function func. The function returns
nil if there is no upvalue with the given index. Otherwise, it returns the name of the upvalue.
str = debug.setupvalue(func, up, value)

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

debug . traceback 2011.6+


Frequently, when an error happens, we want more debug information than only the location where the error
occurred. At least, we want a traceback, showing the complete stack of calls leading to the error. When pcall
returns its error message, it destroys part of the stack (the part that went from it to the error point).
Consequently, if we want a traceback, we must build it before pcall returns. To do that, Lua provides the
xpcall function. Besides the function to be called, it receives a second argument, an error handler function. In
case of errors, Lua calls that error handler before the stack unwinds, so that it can use the debug library to
gather any extra information it wants about the error. Two common error handlers are debug.debug, which
gives you a Lua prompt so that you can inspect by yourself what was going on when the error happened
(later we will see more about that, when we discuss the debug library); and debug.traceback, which builds an
extended error message with a traceback. The latter is the function that the stand-alone interpreter uses to
build its error messages. You also can call debug.traceback at any moment to get a traceback of the current
execution:
str = debug.traceback([message] [, level])

Parameters:
message : (str) message to debug
level : (num) stack level

Result:
str : debug traceback

Gideros API Reference v2017.12 Page 183


file 2011.6+
file object is usually returned by `io.open` used to manipulate (read and write) files in lua

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

file : close 2011.6+


Closes file. Note that files are automatically closed when their handles are garbage collected, but that takes
an unpredictable amount of time to happen.
file:close()

file : flush 2011.6+


Saves any written data to file.
file:flush()

file : lines 2011.6+


Returns an iterator function that, each time it is called, returns a new line from the file. Therefore, the
construction `for line in file:lines() do body end` will iterate over all lines of the file. (Unlike io.lines, this
function does not close the file when the loop ends.)
function = file:lines()
function : iterator function

file : read 2011.6+


Reads the file file, according to the given formats, which specify what to read. For each format, the function
returns a string (or a number) with the characters read, or nil if it cannot read data with the specified format.
When called without formats, it uses a default format that reads the entire next line (see below). The
available formats are "*n": reads a number; this is the only format that returns a number instead of a string.
"*a": reads the whole file, starting at the current position. On end of file, it returns the empty string. "*l": reads
the next line (skipping the end of line), returning nil on end of file. This is the default format. number: reads a
string with up to this number of characters, returning nil on end of file. If number is zero, it reads nothing and
returns an empty string, or nil on end of file.
str = file:read(format1 [, ...])

Parameters:
format1 : (str) format

Gideros API Reference v2017.12 Page 184


... : (str) more optional formats

Result:
str : read string from file

file : seek 2011.6+


Sets and gets the file position, measured from the beginning of the file, to the position given by offset plus a
base specified by the string whence, as follows: "set": base is position 0 (beginning of the file);"cur": base is
current position;"end": base is end of file; In case of success, function seek returns the final file position,
measured in bytes from the beginning of the file. If this function fails, it returns nil, plus a string describing the
error. The default value for whence is "cur", and for offset is 0. Therefore, the call file:seek() returns the
current file position, without changing it; the call file:seek("set") sets the position to the beginning of the file
(and returns 0); and the call file:seek("end") sets the position to the end of the file, and returns its size.
num = file:seek([whence] [, offset])

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

file : write 2011.6+


Writes strings or numbers to file
file:write(value1 [, ...])
value1 : (str) value to write to file
... : (multiple) other optional values to write to file

Gideros API Reference v2017.12 Page 185


int64 2016.08+
64-bit integers as built-in Lua library registered with int64 name. No need to require it.You have 3 ways to
create int64 numbers:#n -- from number, shortcut for int64.new(n)int64.new(n) -- from numberint64.new(s) --
from stringTo convert them back to Lua built-in types:num() -- to numbernum"" -- to stringTo get and set
single bits:num[i]num[i] = bAll operators are supported including new bitwise ones as for Lua double
numbers.

int64 . new 2016.08+


Create 64 bit integer
int64.new(value)
value : (string or number) value to use as 64 bit integer

Gideros API Reference v2017.12 Page 186


io 2011.6+
Manages main input/output operations

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

Gideros API Reference v2017.12 Page 187


Parameter:
filename : (str) filename to open

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

Gideros API Reference v2017.12 Page 188


io . type 2011.6+
Checks whether obj is a valid file handle. Returns the string "file" if obj is an open file handle, "closed file" if
obj is a closed file handle, or nil if obj is not a file handle.
str = io.type(obj)

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

Gideros API Reference v2017.12 Page 189


math 2011.6+
`math` table holds most commonly used math functions and constants

math . abs 2011.6+


Returns the absolute value of v.
num = math.abs(v)

Parameter:
v : (num) number to use for absolute value

Result:
num : absolute value of v

math . acos 2011.6+


Returns the arc cosine of v (in radians).
num = math.acos(v)

Parameter:
v : (num) value to get acos from

Result:
num : acos value of provided value

math . asin 2011.6+


returns arc sine value of v in radians
num = math.asin(v)

Parameter:
v : (num) value to get asin from

Result:
num : asin value from v

math . atan 2011.6+


returns arc tangent value of v in radians
num = math.atan(v)

Parameter:
v : (num) value to get atan from

Result:
num : atan value of v

math . atan2 2011.6+


Returns the arc tangent of v1/v2 (in radians), but uses the signs of both parameters to find the quadrant of
the result. (It also handles correctly the case of v2 being zero.)
num = math.atan2(v1, v2)

Parameters:

Gideros API Reference v2017.12 Page 190


v1 : (num) first value
v2 : (num) second value

Result:
num : result

math . ceil 2011.6+


returns smallest integer >= v
num = math.ceil(v)

Parameter:
v : (num) value to ceil

Result:
num : ceiled value

math . cos 2011.6+


returns cosine value of angle rad
num = math.cos(rad)

Parameter:
rad : (num) angle in radians

Result:
num : result

math . deg 2011.6+


returns angle in degrees of radians rad
num = math.deg(rad)

Parameter:
rad : (num) radian value to convert to degree

Result:
num : result in degree

math . exp 2011.6+


returns e^v
num = math.exp(v)

Parameter:
v : (num) level of exponentiation for e

Result:
num : result of exponentiation

math . floor 2011.6+


returns largest integer <= v
num = math.floor(v)

Parameter:

Gideros API Reference v2017.12 Page 191


v : (num) value to floor

Result:
num : floored value

math . fmod 2011.6+


Returns the remainder of the division of v1 by v2 that rounds the quotient towards zero.
num = math.fmod(v1, v2)

Parameters:
v1 : (num) first value
v2 : (num) second value

Result:
num : remainder of division

math . frexp 2011.6+


Returns m and e such that v = m2^e, e is an integer and the absolute value of m is in the range [0.5, 1) (or
zero when v is zero).
num = math.frexp(v)

Parameter:
v : (num) value

Result:
num : result

math . ldexp 2011.6+


Returns v12^v2 (v2 should be an integer).
num = math.ldexp(v1, v2)

Parameters:
v1 : (num) first value
v2 : (num) second value

Result:
num : result

math . log 2011.6+


returns natural logarithm of v
num = math.log(v)

Parameter:
v : (num) value

Result:
num : result

math . log10 2011.6+


Returns the base-10 logarithm of v

Gideros API Reference v2017.12 Page 192


num = math.log10(v)

Parameter:
v : (num) value

Result:
num : result

math . max 2011.6+


returns maximum in a list of one or more values
num = math.max(v1 [, ...])

Parameters:
v1 : (num) first value
... : (multiple) more optional numbers

Result:
num : highest number of all provided numbers

math . min 2011.6+


returns minimum in a list of one or more values
num = math.min(v1 [, ...])

Parameters:
v1 : (num) firs value
... : (multiple) more optional numbers

Result:
num : smallest number of all provided numbers

math . pow 2011.6+


returns v1 raised to the power of v2
num = math.pow(v1, v2)

Parameters:
v1 : (num) value to exponentiate
v2 : (num) power in which to exponentiate

Result:
num : result of exponentiation

math . rad 2011.6+


returns angle in radians of degrees deg
num = math.rad(deg)

Parameter:
deg : (num) angle in degrees

Result:
num : angle in radians

math . random 2011.6+

Gideros API Reference v2017.12 Page 193


This function is an interface to the simple pseudo-random generator function rand provided by ANSI C. (No
guarantees can be given for its statistical properties.) When called without arguments, returns a uniform
pseudo-random real number in the range [0,1). When called with an integer number m, math.random returns
a uniform pseudo-random integer in the range [1, m]. When called with two integer numbers m and n,
math.random returns a uniform pseudo-random integer in the range [m, n].
num = math.random([n] [, u])

Parameters:
n : (num) upper limit if only n provided, lower limit if u also provided
u : (num) upper limit

Result:
num : pseudo random number

math . randomseed 2011.6+


Sets x as the "seed" for the pseudo-random generator: equal seeds produce equal sequences of numbers.
math.randomseed(seed)
seed : (num) seed for random number generator

math . sin 2011.6+


returns sine value of angle rad
num = math.sin(rad)

Parameter:
rad : (num) angle in radians

Result:
num : sine of provided angle

math . sqrt 2011.6+


returns square root of v
num = math.sqrt(v)

Parameter:
v : (num) value to compute the square root for

Result:
num : square root

math . tan 2011.6+


returns tangent value of angle rad
num = math.tan(rad)

Parameter:
rad : (num) angle in radians

Result:
num : tangent of the angle

Gideros API Reference v2017.12 Page 194


os 2011.6+
Operating System Facilities

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

Gideros API Reference v2017.12 Page 195


the success code.
os.exit([code])
code : (str) exit code

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

Gideros API Reference v2017.12 Page 196


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`.
num = os.time([table])

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

Gideros API Reference v2017.12 Page 197


package 2011.6+
Table containing manipulations for packages/modules/libraries

package . loadlib 2011.6+


Dynamically links the host program with the C library libname. Inside this library, looks for a function
funcname and returns this function as a C function. (So, funcname must follow the protocol (see
lua_CFunction)). This is a low-level function. It completely bypasses the package and module system. Unlike
require, it does not perform any path searching and does not automatically adds extensions. libname must be
the complete file name of the C library, including if necessary a path and extension. funcname must be the
exact name exported by the C library (which may depend on the C compiler and linker used). This function is
not supported by ANSI C. As such, it is only available on some platforms (Windows, Linux, Mac OS X,
Solaris, BSD, plus other Unix systems that support the dlfcn standard).
package.loadlib(libname, funcname)
libname : (str) name of the library to load
funcname : (str) name of the function in library

Gideros API Reference v2017.12 Page 198


string 2011.6+
This library provides generic functions for string manipulation, such as finding and extracting substrings, and
pattern matching. When indexing a string in Lua, the first character is at position 1 (not at 0, as in C). Indices
are allowed to be negative and are interpreted as indexing backwards, from the end of the string. Thus, the
last character is at position -1, and so on. The string library provides all its functions inside the table string. It
also sets a metatable for strings where the __index field points to the string table. Therefore, you can use the
string functions in object-oriented style. For instance, string.byte(s, i) can be written as s:byte(i). The string
library assumes one-byte character encodings.

string . byte 2011.6+


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. Note that numerical codes are not necessarily portable across platforms.
numbers = string.byte(s [, i] [, j])

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

string . char 2011.6+


Receives zero or more integers. 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. Note that numerical
codes are not necessarily portable across platforms.
str = string.char(i1 [, i2] [, ...])

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

string . dump 2011.6+


Returns a string containing a binary representation of the given function, so that a later loadstring on this
string returns a copy of the function. function must be a Lua function without upvalues.
str = string.dump(function)

Parameter:
function : (function) function to convert to string

Result:
str : string representation of function

string . find 2011.6+


Looks for the first match of pattern in the string s. If it finds a match, then find returns the indices of s where

Gideros API Reference v2017.12 Page 199


this 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 a fourth, optional
argument plain turns off the pattern matching facilities, so the function does 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.
numbers = string.find(s, pattern [, init] [, plain])

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

string . format 2011.6+


Returns a formatted version of its variable number of arguments following the description given in its first
argument (which must be a string). The format string follows the same rules as the printf family of standard C
functions. The only differences are that the options/modifiers *, l, 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: the string is written between double quotes, and all double quotes, newlines, embedded zeros,
and backslashes in the string are correctly escaped when written. For instance, the call `string.format('%q',
'a string with "quotes" and \n new line')` will produce the string: `"a string with \"quotes\" and \ new line"`
The options c, d, E, e, f, g, G, i, o, u, X, and x all expect a number as argument, whereas q and s expect a
string. This function does not accept string values containing embedded zeros, except as arguments to the q
option.
string.format(formatstring [, e1] [, e2] [, ...])
formatstring : (str) the string defining the format of the output
e1 : (str) first parameter for the format string
e2 : (str) second parameter to format string
... : (multiple) more optional parameters for format string

string . gmatch 2011.6+


Returns an iterator function that, each time it is called, returns the next captures from pattern over string s. If
pattern specifies no captures, then the whole match is produced in each call. As an example, the following
loop `s = "hello world from Lua"` `for w in string.gmatch(s, "%a+") do` `print(w)` `end`</pre> will
iterate over all the words from string s, printing one per line. The next example collects all pairs key=value
from the given string into a table: `t = {}` `s = "from=world, to=Lua"` `for k, v in string.gmatch(s,
"(%w+)=(%w+)") do` `t[k] = v` `end` For this function, a '^' at the start of a pattern does not work as an
anchor, as this would prevent the iteration.
function = string.gmatch(s, pat)

Parameters:
s : (str) string where to look for patterns
pat : (str) pattern to look for

Result:
function : iterator function

Gideros API Reference v2017.12 Page 200


string . gsub 2011.6+
Returns a copy of s in which all (or the first n, if given) occurrences of the pattern 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. 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 %n, with n
between 1 and 9, stands for the value of the n-th captured substring (see below). 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 the pattern specifies no captures, then the whole match is
used 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; if the pattern specifies no captures, then the whole match is
passed as a sole argument. 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). Here are some examples: `x = string.gsub("hello world",
"(%w+)", "%1 %1") --> x="hello hello world world"` `x = string.gsub("hello world", "%w+", "%0 %0", 1) -->
x="hello hello world"` `x = string.gsub("hello world from Lua", "(%w+)%s*(%w+)", "%2 %1") --> x="world
hello Lua from"` `x = string.gsub("home = $HOME, user = $USER", "%$(%w+)", os.getenv)``--> x="home =
/home/roberto, user = roberto"` `x = string.gsub("4%2B5 = $return 4%2B5$", "%$(.-)%$", function (s) return
loadstring(s)() end) --> x="4%2B5 = 9"``local t = {name="lua", version="5.1"}``x =
string.gsub("$name-$version.tar.gz", "%$(%w+)", t) --> x="lua-5.1.tar.gz"`
str = string.gsub(s, pat, repl [, n])

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

string . len 2011.6+


Receives a string and returns its length. The empty string "" has length 0. Embedded zeros are counted, so
"a\000bc\000" has length 5.
num = string.len(s)

Parameter:
s : (str) string for which to measure length

Result:
num : the length of the string

string . lower 2011.6+


Receives a string and returns a copy of this string with all uppercase letters changed to lowercase. All other
characters are left unchanged. The definition of what an uppercase letter is depends on the current locale.
str = string.lower(s)

Parameter:
s : (str) string to modify

Result:
str : lowercased string

Gideros API Reference v2017.12 Page 201


string . match 2011.6+
Find the first match of the regular expression "pattern" in "str", starting at position "index".The starting position
(index) is optional, and defaults to 1 (the start of the string).If found, returns any captures in the pattern. If no
captures were specified the entire matching string is returned.If not found, returns nil.This is similar to
string.find, except that the starting and ending index are not returned.print (string.match ("You see dogs and
cats", "s..")) --> see
str = string.match(str, pattern)

Parameters:
string : (str) Any string.
pattern : (str) Specifies the pattern to match.

Result:
str : String matching pattern.

string . rep 2011.6+


Returns a string that is the concatenation of n copies of the string s.
str = string.rep(s, n)

Parameters:
s : (str) string to copy
n : (num) how many times to copy a string

Result:
str : concatenated by n copies

string . sub 2011.6+


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.
str = string.sub(s, i [, j])

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

string . upper 2011.6+


Make all the lower case characters upper case.
str = string.upper(s)

Parameter:
s : (str) string to modify

Result:
str : uppercased string

Gideros API Reference v2017.12 Page 202


table 2011.6+
This library provides generic functions for table manipulation. It provides all its functions inside the table table.
Most functions in the table library assume that the table represents an array or a list. For these functions,
when we talk about the "length" of a table we mean the result of the length operator.

table . concat 2011.6+


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.
str = table.concat(table [, sep] [, i] [, j])

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

table . getn 2011.6+


returns size of table, or n field, or table.setn value, or 1 less first index with nil value\n [Deprecated in Lua 5.1,
use # operator]
table.getn(table)
table : (any)

table . insert 2011.6+


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 [, pos] [, value])
table : (table) table where to insert new element
pos : (num) index where to insert new element
value : (any) value to insert in table

table . remove 2011.6+


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.
varies = table.remove(table [, pos])

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

Gideros API Reference v2017.12 Page 203


table . sort 2011.6+
Sort the elements of a table in-place (i.e. alter the table). `> t = { 3,2,5,1,4 }``> table.sort(t)``> = table.concat(t,
", ") -- display sorted values``1, 2, 3, 4, 5`A comparison function can be provided to customise the element
sorting. The comparison function must return a boolean value specifying whether the first argument should be
before the second argument in the sequence. The default behaviour is for the < comparison to be made. For
example, the following behaves the same as no function being supplied:
table.sort(table [, comp])
table : (table) table to sort
comp : (function) comparison function returning bool comparison result

Gideros API Reference v2017.12 Page 204


utf8 2016.06+
utf8 string library

utf8 . byte 2016.06+


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 function string.sub.Numerical
codes are not necessarily portable across platforms.
numbers = utf8.byte(s [, i] [, j])

Parameters:
s : (str)
i : (num) default is 1
j : (num)

Result:
numbers : Returns the internal numerical codes of the characters

utf8 . char 2016.06+


Receives zero or more integers. 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.Numerical codes are not
necessarily portable across platforms.
str = utf8.char(code1 [, code2] [, codeN])

Parameters:
code1 : (num)
code2 : (num)
codeN : (num)

Result:
str : string with provided characters

utf8 . charpos 2016.06+


convert UTF-8 position to byte offset. if only offset is given, return byte offset of this UTF-8 char index. if
charpos and offset is given, a new charpos will calculate, by add/subtract UTF-8 char offset to current
charpos. in all case, it return a new char position, and code point (a number) at this position.
num = utf8.charpos(s [, charpos] [, offset])

Parameters:
s : (str)
charpos : (num)
offset : (num)

Result:
num : return byte offset of this UTF-8 char index

utf8 . codepoint 2016.06+


Returns the codepoints (as integers) from all characters in s that start between byte position i and j (both
included). The default for i is 1 and for j is i. It raises an error if it meets any invalid byte sequence.
numbers = utf8.codepoint(s [, i] [, j])

Gideros API Reference v2017.12 Page 205


Parameters:
s : (str)
i : (num)
j : (num)

Result:
numbers : Returns the codepoints (as integers) from all characters in s

utf8 . codes 2016.06+


Returns values so that the constructionfor p, c in utf8.codes(s) do body endwill iterate over all characters in
string s, with p being the position (in bytes) and c the code point of each character. It raises an error if it
meets any invalid byte sequence.
iterator = utf8.codes(s)

Parameter:
s : (str)

Result:
iterator

utf8 . escape 2016.06+


Escape a str to UTF-8 format string. It support several escape format:%ddd - which ddd is a decimal number
at any length: change Unicode code point to UTF-8 format. %{ddd} - same as %nnn but has bracket around.
%uddd - same as %ddd, u stands Unicode %u{ddd} - same as %{ddd} %xhhh - hexadigit version of %ddd
%x{hhh} same as %xhhh. %? - '?' stands for any other character: escape this character.
str = utf8.escape(s)

Parameter:
s : (str)

Result:
str : escaped string

utf8 . find 2016.06+


Looks for the first match of pattern in the string s. If it finds a match, then find returns the indices of s where
this 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 a fourth, optional
argument plain turns off the pattern matching facilities, so the function does 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.
numbers = utf8.find(s, pattern [, init] [, plain])

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

Gideros API Reference v2017.12 Page 206


utf8 . fold 2016.06+
convert UTF-8 string s to folded case used to compare by ignore case. if s is a number, it's treat as a code
point and return a convert code point (number). utf8.lower/utf8.upper has the same extension.
str = utf8.fold(s)

Parameter:
s : (str)

Result:
str : folded case string

utf8 . gmatch 2016.06+


Returns an iterator function that, each time it is called, returns the next captures from pattern over the string
s. If pattern specifies no captures, then the whole match is produced in each call.For this function, a caret '^'
at the start of a pattern does not work as an anchor, as this would prevent the iteration.
function = utf8.gmatch(s, pattern)

Parameters:
s : (str)
pattern : (str)

Result:
function : iterator function

utf8 . gsub 2016.06+


Returns a copy of s in which all (or the first n, if given) occurrences of the pattern 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).
str, num = utf8.gsub(s, pattern, repl [, n])

Parameters:
s : (str)
pattern : (str)
repl : (varies)
n : (num)

Results:
str : replaced string
num : number of substitutions

utf8 . insert 2016.06+


Insert a substring to s. If idx is given, insert substring before char at this index, otherwise substring will concat

Gideros API Reference v2017.12 Page 207


to s. idx can be negative.
str = utf8.insert(s [, idx] [, substring])

Parameters:
s : (str)
idx : (num) index where to insert
substring : (str)

Result:
str : new string

utf8 . len 2016.06+


Returns the number of UTF-8 characters in string s that start between positions i and j (both inclusive). The
default for i is 1 and for j is -1. If it finds any invalid byte sequence, returns a false value plus the position of
the first invalid byte.
num = utf8.len(s [, i] [, j])

Parameters:
s : (str)
i : (num)
j : (num)

Result:
num : number of characters

utf8 . lower 2016.06+


Receives a string and returns a copy of this string with all uppercase letters changed to lowercase. All other
characters are left unchanged. The definition of what an uppercase letter is depends on the current locale.
str = utf8.lower(s)

Parameter:
s : (str)

Result:
str : lowercased string

utf8 . match 2016.06+


Looks for the first match of pattern in the string s. If it finds one, then 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 value is 1 and can be
negative.
strings = utf8.match(s, pattern [, init])

Parameters:
s : (str)
pattern : (str)
init : (num)

Result:
strings : captures

utf8 . ncasecmp 2016.06+

Gideros API Reference v2017.12 Page 208


Compare a and b without case, -1 means a < b, 0 means a == b and 1 means a > b.
num = utf8.ncasecmp(a, b)

Parameters:
a : (str)
b : (str)

Result:
num : compare state

utf8 . next 2016.06+


Iterate though the UTF-8 string s. If only s is given, it can used as a iterator:for pos, code in utf8.next,
"utf8-string" do-- ...endif only charpos is given, return the next byte offset of in string. if charpos and offset is
given, a new charpos will calculate, by add/subtract UTF-8 char offset to current charpos. in all case, it return
a new char position (in bytes), and code point (a number) at this position.
varies = utf8.next(s [, charpos] [, offset])

Parameters:
s : (str)
charpos : (num)
offset : (num)

Result:
varies : next iteration

utf8 . offset 2016.06+


Returns the position (in bytes) where the encoding of the n-th character of s (counting from position i) starts.
A negative n gets characters before position i. The default for i is 1 when n is non-negative and #s + 1
otherwise, so that utf8.offset(s, -n) gets the offset of the n-th character from the end of the string. If the
specified character is neither in the subject nor right after its end, the function returns nil.As a special case,
when n is 0 the function returns the start of the encoding of the character that contains the i-th byte of s.This
function assumes that s is a valid UTF-8 string.
num = utf8.offset(s, n [, i])

Parameters:
s : (str)
n : (num)
i : (num)

Result:
num : position (in bytes)

utf8 . remove 2016.06+


Delete a substring in s. If neither start nor stop is given, delete the last UTF-8 char in s, otherwise delete char
from start to end of s. if stop is given, delete char from start to stop (include start and stop). start and stop can
be negative
utf8.remove(s [, start] [, stop])
s : (str)
start : (num)
stop : (num)

Gideros API Reference v2017.12 Page 209


utf8 . reverse 2016.06+
Returns a string that is the string s reversed.
str = utf8.reverse(s)

Parameter:
s : (str)

Result:
str : reversed string

utf8 . sub 2016.06+


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.If, after the translation
of negative indices, i is less than 1, it is corrected to 1. If j is greater than the string length, it is corrected to
that length. If, after these corrections, i is greater than j, the function returns the empty string.
str = utf8.sub(s, i [, j])

Parameters:
s : (str)
i : (num)
j : (num)

Result:
str : substring of s that starts at i and continues until j

utf8 . title 2016.06+


Convert UTF-8 string s to title case used to compare by ignore case. if s is a number, it's treat as a code point
and return a convert code point (number). utf8.lower/utf8.upper has the same extension.
str = utf8.title(s)

Parameter:
s : (str)

Result:
str : string in title case

utf8 . upper 2016.06+


Receives a string and returns a copy of this string with all lowercase letters changed to uppercase. All other
characters are left unchanged. The definition of what a lowercase letter is depends on the current locale.
str = utf8.upper(s)

Parameter:
s : (str)

Result:
str : string in upper case

utf8 . width 2016.06+


calculate the width of UTF-8 string s. if ambi_is_double is given, the ambiguous width character's width is 2,

Gideros API Reference v2017.12 Page 210


otherwise it's 1. fullwidth/doublewidth character's width is 2, and other character's width is 1. if default_width
is given, it will be the width of unprintable character, used display a non-character mark for these characters.
if s is a code point, return the width of this code point.
num = utf8.width(s [, ambi_is_double] [, default_width])

Parameters:
s : (str)
ambi_is_double : (bool)
default_width : (num)

Result:
num : width

utf8 . widthindex 2016.06+


Return the character index at given location in string s. this is a reverse operation of utf8.width(). this function
return a index of location, and a offset in in UTF-8 encoding. e.g. if cursor is at the second column (middle) of
the wide char, offset will be 2. the width of character at idx is returned, also.
num = utf8.widthindex(s, location [, ambi_is_double] [, default_width])

Parameters:
s : (str)
location : (num)
ambi_is_double : (bool)
default_width : (num)

Result:
num : character index at given location

Gideros API Reference v2017.12 Page 211


zlib 2015.04.18+
Zlib lua binding from <a
href='https://github.com/LuaDist/lzlib/blob/master/README'>https://github.com/LuaDist/lzlib/blob/master/REA
DME</a>

zlib . adler32 2015.04.18+


Without any parameters, returns the inicial adler32 value.Call to update the adler32 value, adler is the current
value, buffer is passed to adler32 zlib function and the updated value is returned.
str = zlib.adler32([adler32] [, buffer])

Parameters:
adler32 : (num) adler value
buffer : (str) buffer to modify value for

Result:
str : without parameters returns initial value

zlib . compress 2015.04.18+


Return a string containing the compressed buffer according to the given parameters.
str = zlib.compress(buffer [, level] [, method] [, windowBits] [, memLevel] [, strategy])

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

zlib . crc32 2015.04.18+


Without any parameters, returns the inicial crc32 value.Call to update the crc32 value, crc is the current
value, buffer is passed to crc32 zlib function and the updated value is returned.
str = zlib.crc32([crc32] [, buffer])

Parameters:
crc32 : (num) crc32 value
buffer : (str) buffer to modify value

Result:
str : without parameters returns initial value

zlib . decompress 2015.04.18+


Return the decompressed stream after processing the given buffer.
str = zlib.decompress(buffer [, windowBits])

Gideros API Reference v2017.12 Page 212


Parameters:
buffer : (str) buffer to deflate
windowBits : (num) from 8 to 15, larger values of this parameter result in better compression at the expense
of memory usage
Result:
str : decompressed buffer

zlib . deflate 2015.04.18+


Return a deflate stream.
stream = zlib.deflate(sink [, level] [, method] [, windowBits] [, memLevel] [, strategy] [, dictionary])

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

zlib . inflate 2015.04.18+


Return an inflate stream.
stream = zlib.inflate(source [, windowBits] [, dictionary])

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

Gideros API Reference v2017.12 Page 213


Plugins
This is a decription of the various Plugins and how they work.

Gideros API Reference v2017.12 Page 214


Ads Inherits: EventDispatcher 2011.6+
The idea is to provide common Ads interface for most of available ad frameworks, so that user's would not
have to create a plugin for each of them separately, but rather it would be possible to wrap ad framework in
single Java or Objective-C class (depending on the platform) and add it to the project, without even
recompiling existing Ads Interface plugin.Additionally it would be able to support multiple ad frameworks
simultaneously so users could switch and fall back between ad frameworks on runtime.More information
available in [http://docs.giderosmobile.com/interface/ads](Ads interface guide).

Creating fallbacks with Ads frameworks


--require plugin
require "ads"

--initialize amazon
amazon=Ads.new("amazon")
amazon:setKey("amazon-key")

--initialize admob
admob=Ads.new("admob")
admob:setKey("admob-key")

--if amazon fails


--show admob
amazon:addEventListener(Event.AD_FAILED, function(e)
print("amazon AD_FAILED", e.error)
admob:showAd("auto")
end)

--if admob fails


--show amazon
admob:addEventListener(Event.AD_FAILED, function(e)
print("admob AD_FAILED", e.error)
amazon:showAd("auto")
end)

--start displaying amazon ads


amazon:showAd("auto");

Ads . new 2014.01+


Initializes new ad frameworkFor the possible values check [http://docs.giderosmobile.com/interface/ads](Ads
Interface Guide)
Ads.new(adframework)
adframework : (str) name of the adframework

Ads : enableTesting 2011.6+


Enable testing ads if supported by framework
Ads:enableTesting()

Ads : get 2011.6+

Gideros API Reference v2017.12 Page 215


Gets property value of the ad (accepted values x, y)
varies = Ads:get(property)

Parameter:
property : (str) value for which property to get

Result:
varies : value of the property

Ads : getHeight 2011.6+


Gets the height of the ad in Gideros logical dimensions, taking into consideration applied automatic scaling
num = Ads:getHeight()
num : height of the banner ad

Ads : getPosition 2011.6+


Gets x and y position of the ad in Gideros logical dimensions, taking into consideration applied automatic
scaling
num, num = Ads:getPosition()
num : x position of the ad
num : y position of the ad

Ads : getWidth 2014.01+


Gets width of the ad in Gideros logical dimensions, taking into consideration applied automatic scaling
num = Ads:getWidth()
num : width of the banner ad

Ads : getX 2014.01+


Gets x position of the ad in Gideros logical dimensions, taking into consideration applied automatic scaling
num = Ads:getX()
num : x position of the ad

Ads : getY 2014.01+


Gets y position of the ad in Gideros logical dimensions, taking into consideration applied automatic scaling
num = Ads:getY()
num : get y position of the ad

Ads : hideAd 2014.01+


Hides displayed ads
Ads:hideAd()

Ads : set 2011.6+


Sets property value of the ad (accepted values: x, y)
Ads:set(property, value)

Gideros API Reference v2017.12 Page 216


property : (str) name of the property to set
value : (varies) value to set

Ads : setAlignment 2014.01+


Sets alignment of the adFirst value is for the horizontal alignment and can have values as "left", "center",
"right"Second value is for the vertical alignment and can have values as "top", "center", "bottom"
Ads:setAlignment(horizontal, vertical)
horizontal : (strong) horizontal alignment
vertical : (str) vertical alignment

Ads : setKey 2014.01+


provide all the keys/appids/etc needed for the framework, which you will get in same order on Native part in
Map/Array objectFor the possible values check [http://docs.giderosmobile.com/interface/ads](Ads Interface
Guide) Methods tab
Ads:setKey(...)
... : (values) Varies for each ad framework

Ads : setPosition 2014.01+


Sets position of the ad in Gideros logical dimensions, taking into consideration applied automatic scaling
Ads:setPosition(x, y)
x : (num) x position to set
y : (num) y position to set

Ads : setX 2014.01+


Sets x position of the ad in Gideros logical dimensions, taking into consideration applied automatic scaling
Ads:setX(x)
x : (num) set x coordinate

Ads : setY 2014.01+


Sets y position of the ad in Gideros logical dimensions, taking into consideration applied automatic scaling
Ads:setY(y)
y : (num) set y coordinate

Ads : showAd 2011.6+


Display provided ad type with any other additional information.For the possible values check
[http://docs.giderosmobile.com/interface/ads](Ads Interface Guide) Methods tab
Ads:showAd(...)
... : (varies) varies for each ad framework

Gideros API Reference v2017.12 Page 217


bit 2013.09+
Provides bit based operations

bit . arshift 2013.09+


Returns the bitwise arithmetic right-shift by the number of bits given by the second argument.
num = bit.arshift(x, n)

Parameters:
x : (num) number to shift
n : (num) amount of bits to shift

Result:
num : bitwise arithmetic right-shift

bit . band 2013.09+


Returns the bitwise and of its argument.
num = bit.band(x1 [, x2])

Parameters:
x1 : (num) first number for and operation
x2 : (num) second and more numbers can be provided for and operation

Result:
num : bitwise and

bit . bnot 2013.09+


Returns the bitwise not of its argument.
num = bit.bnot(x)

Parameter:
x : (num) number to which to apply bitwise not

Result:
num : bitwise not

bit . bor 2013.09+


Returns the bitwise or of its argument.
num = bit.bor(x1 [, x2])

Parameters:
x1 : (num) first number for or operation
x2 : (num) second and more numbers can be provided for or operation

Result:
num : bitwise or

bit . bswap 2013.09+


Swaps the bytes of its argument and returns it. This can be used to convert little-endian 32 bit numbers to
big-endian 32 bit numbers or vice versa.

Gideros API Reference v2017.12 Page 218


num = bit.bswap(x)

Parameter:
x : (num) number to swap

Result:
num : Swapped bytes

bit . bxor 2013.09+


Returns the bitwise xor of its argument.
num = bit.bxor(x1 [, x2])

Parameters:
x1 : (num) first number for xor operation
x2 : (num) second and more numbers can be provided for xor operation

Result:
num : bitwise xor

bit . lshift 2013.09+


Returns the bitwise logical left-shift by the number of bits given by the second argument.
num = bit.lshift(x, n)

Parameters:
x : (num) number to shift
n : (num) amount of bits to shift

Result:
num : bitwise logical left-shift

bit . rol 2013.09+


Returns the bitwise left rotation of its first argument by the number of bits given by the second argument. Bits
shifted out on one side are shifted back in on the other side.
num = bit.rol(x, n)

Parameters:
x : (num) number to rotate
n : (num) amount of bits to rotate

Result:
num : bitwise left rotation

bit . ror 2013.09+


Returns the bitwise right rotation of its first argument by the number of bits given by the second argument.
Bits shifted out on one side are shifted back in on the other side.
num = bit.ror(x, n)

Parameters:
x : (num) number to rotate
n : (num) amount of bits to rotate

Result:

Gideros API Reference v2017.12 Page 219


num : bitwise right rotation

bit . rshift 2013.09+


Returns the bitwise logical right-shift by the number of bits given by the second argument.
num = bit.rshift(x, n)

Parameters:
x : (num) number to shift
n : (num) amount of bits to shift

Result:
num : bitwise logical right-shift

bit . tobit 2013.09+


Normalizes a number to the numeric range for bit operations and returns it. This function is usually not
needed since all bit operations already normalize all of their input arguments.
num = bit.tobit(x)

Parameter:
x : (num) number which range to normalize

Result:
num : normalized number

bit . tohex 2013.09+


Converts its first argument to a hex string. The number of hex digits is given by the absolute value of the
optional second argument. Positive numbers between 1 and 8 generate lowercase hex digits. Negative
numbers generate uppercase hex digits. Only the least-significant 4*|n| bits are used. The default is to
generate 8 lowercase hex digits.
str = bit.tohex(x [, n])

Parameters:
x : (num) number to convert to hex string
n : (num) number of hex digits to convert

Result:
str : hex string

Gideros API Reference v2017.12 Page 220


bump 2017.8+
This is a native (and much faster) implementation of excellent bump.lua collision library. See full original
documentations here: https://github.com/kikito/bump.lua Just require 'cbump' instead of 'bump' to use this
native version.

Gideros API Reference v2017.12 Page 221


camera 2017.8+
Renders live camera stream into a Texture

Example:
require "camera"

-- Probe camera size (use a dummy 512x512 surface)


Camera.texture=Texture.new(nil,512,512)
cw,ch=Camera.start(Camera.texture)
Camera.stop()

-- Restart camera with a full sized texture


Camera.texture=Texture.new(nil,cw,ch,true)
cw,ch=Camera.start(Camera.texture)

application:setLogicalDimensions(ch,cw)

local b=Bitmap.new(Camera.texture)
stage:addChild(b)

camera . availableDevices 2017.8+


Returns a list of tables describing each available camera in the system. Each list entry has the following
fields:*name* - Internal name of the device*description* - Description of the device*position* - Position of
the device, can be 'front','back' or 'unknown'
table = camera.availableDevices()
table : List of available cameras

camera . start 2017.8+


Start live streaming of camera images to the specified Texture.
num, num = camera.start(texture [, device])

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

camera . stop 2017.8+


Stops live camera streaming and releases resources.
camera.stop()

Gideros API Reference v2017.12 Page 222


Controller Inherits: EventDispatcher 2014.01+
Controller interface allows you to use most popular controllers on all supported operating systems under the
same interface.Internally Controller Interface also matches all buttons and controller behavior under the same
scheme so you won't have to worry about that anymore.For more information check out
[http://docs.giderosmobile.com/interface/controller](Controller Interface Guide)

Using Controller example


require "controller"

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)

Controller : getControllerName 2014.01+


Get the name of controller

Gideros API Reference v2017.12 Page 223


str = Controller:getControllerName(id)

Parameter:
id : (num) controller id

Result:
str : controller name

Controller : getPlayerCount 2014.01+


Returns amount of connected controllers
num = Controller:getPlayerCount()
num : amount of connected controllers

Controller : getPlayers 2014.01+


Returns table with controller IDs
table = Controller:getPlayers()
table : indexed table with controller ids as values

Controller : isAnyAvailable 2014.01+


Returns true if any of controller is connected to device
bool = Controller:isAnyAvailable()
bool : if any controller is connected

Controller : vibrate 2014.01+


Vibrate the controller for provided amount of miliseconds. Works only if it is supported by the platform and
controller, don't rely on it to work, and only use as addition to the game play
Controller:vibrate(ms)
ms : (num) time in miliseconds

Gideros API Reference v2017.12 Page 224


Facebook Inherits: EventDispatcher 2012.09+
Facebook SDK plugin is available for only iOS as an external plugin. To use facebook module:1. Download
and install Facebook SDK from https://developers.facebook.com/ios/downloads/2. Add
FacebookSDK.framework to your project.3. Add the backward compatibility headers as described
https://developers.facebook.com/docs/howtos/feed-dialog-using-ios-sdk/#step24. Add {Gideros Installation
Directory}/All Plugins/Facebook/source/iOS/* files to your Xcode project.5. If enabled, disable 'Application
does not run in background' property in .plist file.The `Facebook` class is defined in module 'facebook'.
Therefore, you need to call`require('facebook')` before using it. Loading the Facebook module also creates a
global variable `facebook` of type `Facebook` for direct use.

Facebook : authorize 2012.09+


Starts the authorization flow for the user with the requested permissions.
Facebook:authorize(permissions)
permissions : (table, optional) An array of the requested permissions.

Facebook : dialog 2012.09+


Generate a UI dialog for the desired action.
Facebook:dialog(action, paramaters)
action : (str) The type of dialog to call. Currently supported methods are oauth, feed, and apprequests.
paramaters : (table, optional) Table representing parameters specific to a particular dialog.

Facebook : extendAccessToken 2012.09+


Extends the access token.
Facebook:extendAccessToken()

Facebook : extendAccessTokenIfNeeded 2012.09+


Attempts to extend the access token. The access token expires after a certain amount of time and when you
call this method it will be refreshed if it is still active and only after some time has passed since the last
refresh. To ensure that you keep the access token fresh for active users, call this method in your
`Application.RESUME` event.
Facebook:extendAccessTokenIfNeeded()

Facebook : getAccessToken 2012.09+


Returns the access token.
str = Facebook:getAccessToken()
str : The access token.

Facebook : getExpirationDate 2012.09+


Returns the expiration date;
str = Facebook:getExpirationDate()
str : The expiration date if it's set, `nil` otherwise.

Gideros API Reference v2017.12 Page 225


Facebook : graphRequest 2012.09+
Makes a request to the Graph API.
Facebook:graphRequest(graphPath, paramaters, method)
graphPath : (str) The path to the Graph API endpoint. For example, to fetch data about the currently logged in
user this parameter should be ''me'', representing a call to the https://graph.facebook.com/me endpoint.
paramaters : (table, optional) Table representing the API call parameters.
method : (string, optional) HTTP method.

Facebook : isSessionValid 2012.09+


Checks if the access token is available and has not expired.
bool = Facebook:isSessionValid()
bool : `true` if the access token is valid, `false` otherwise.

Facebook : logout 2012.09+


Invalidates the current user session. This method does not unauthorized the application, it simply invalidates
the access token. The user can unauthorized the application through the app settings page on the Facebook
website.
Facebook:logout()

Facebook : setAccessToken 2012.09+


Sets the access token.
Facebook:setAccessToken(accessToken)
accessToken : (str)

Facebook : setAppId 2012.09+


Initializes the Facebook library and sets App ID. This function should be called first before other functions.
Facebook:setAppId(appId)
appId : (str) The Facebook application id.

Facebook : setExpirationDate 2012.09+


Sets the expiration date.
Facebook:setExpirationDate(expirationDate)
expirationDate : (str)

Facebook : shouldExtendAccessToken 2012.09+


Returns if the access token should be extended.
bool = Facebook:shouldExtendAccessToken()
bool : `true` if the access token should be extended, `false` otherwise.

Gideros API Reference v2017.12 Page 226


flurry 2011.6+
This table stores all the functions related to Flurry analytics library.Flurry is available only for iOS as an
external plugin. To use flurry:1. Create an account on [http://www.flurry.com](http://www.flurry.com) and
follow the instructions about creating a new application.2. Download Flurry header and libraries and add
them to your Xcode project.3. Add {Gideros Installation Directory}/All Plugins/Flurry/source/iOS/flurry.mm file
to your Xcode project.To load the Flurry library, call `require 'flurry'`.

flurry . endTimedEvent 2011.6+


Use this function to end timed event before app exists, otherwise timed events automatically end when app
exists. When ending the timed event, a new event parameters table can be used to update event
parameters. If you don't specify a new event parameters table, event parameters are kept the same.
flurry.endTimedEvent(eventName, parameters)
eventName : (str) The event name of end timed event.
parameters : (table, optional) If specified, event paramaters updated for this event.

flurry . isAvailable 2011.6+


Returns `true` if Flurry is available for this platform. Currently, Flurry is available only for iOS.
bool = flurry.isAvailable()
bool : `true` if Flurry is available for this platform, `false` otherwise.

flurry . logEvent 2011.6+


Use this function to count the number of times certain events happen during a session of your application and
to pass dynamic parameters to be recorded with that event. Event parameters is optional and can be passed
in as a table value. Your application is currently limited to counting occurrences for 100 different event ids
(maximum length 255 characters). Maximum of 10 event parameters per event is supported.To start a timed
event, pass `timed` parameter as `true`.
flurry.logEvent(eventName, parameters, timed)
eventName : (str) The event name to be logged at Flurry service.
parameters : (table, optional) Optional paramaters to be recorted with this event.
timed : (boolean, optional) Specifies this is a timed event.

Example:
flurry.logEvent('myEvent1')
flurry.logEvent('myEvent2', {key='value'})
flurry.logEvent('myEvent3', {key='value'}, true)

flurry . startSession 2011.6+


Starts the Flurry session with your API key. To create an account on Flurry and to obtain the API key specific
to your application,please visit [http://www.flurry.com](http://www.flurry.com) and follow the instructions
there.You need to call this function once after your application starts. For example, `init.lua` is suitable to
call this function.
flurry.startSession(apiKey)
apiKey : (str) The Flurry API key.

Gideros API Reference v2017.12 Page 227


GoogleBilling 2012.09+
The `GoogleBilling` class is defined in the module 'googlebilling'. Therefore, you need to
call`require('googlebilling')` before using it. Loading the Google Billing module also creates a global variable
`googlebilling` of type `GoogleBilling` for direct use. <h3>GoogleBilling Events and Response
Codes</h3>`GoogleBilling` class dispatches 5 events:
`Event.CHECK_BILLING_SUPPORTED_COMPLETE`,`Event.REQUEST_PURCHASE_COMPLETE`,`Even
t.RESTORE_TRANSACTIONS_COMPLETE`,`Event.CONFIRM_NOTIFICATION_COMPLETE` and
`Event.PURCHASE_STATE_CHANGE`.`Event.*_COMPLETE` events contains a field
`event.responseCode` which provides status information and error information about a request. Response
code can be one of these values:<ul><li>`GoogleBilling.OK`: Indicates that the request was sent to the
server successfully. When this code is returned</li></ul>in response to a `checkBillingSupported` function,
indicates that billing is supported.<ul><li>`GoogleBilling.USER_CANCELED`: Indicates that the user
pressed the back button on the checkout page instead of buying the
item.</li><li>`GoogleBilling.SERVICE_UNAVAILABLE`: Indicates that the network connection is
down.</li><li>`GoogleBilling.BILLING_UNAVAILABLE`: Indicates that in-app billing is not available because
the API version that</li></ul>you specified is not recognized by the Google Play application or the user is
ineligible for in-app billing (for example, the user resides in a country that prohibits in-app
purchases).<ul><li>`GoogleBilling.ITEM_UNAVAILABLE`: Indicates that Google Play cannot find the
requested item in the application's product list.</li></ul>This can happen if the product ID is misspelled in
your `requestPurchase` function or if an item is unpublished in the application's product
list.<ul><li>`GoogleBilling.DEVELOPER_ERROR`: Indicates that an application is trying to make an in-app
billing request but the application has not declared the</li></ul>com.android.vending.BILLING permission in
its manifest. Can also indicate that an application is not properly signed, or that you sent a malformed
request, such as a request with missing Bundle keys or a request that uses an unrecognized request
type.<ul><li>`GoogleBilling.ERROR`: Indicates an unexpected server error. For example, this error is
triggered if you try to purchase an item from yourself, which is not allowed by Google
Wallet.</li></ul><h3># Event.CHECK_BILLING_SUPPORTED_COMPLETE</h3>Dispatched when
`checkBillingSuported` function completes. It contains `event.responseCode` and `event.productType`
fields.<h3># Event.REQUEST_PURCHASE_COMPLETE</h3>Dispatched when `requestPurchase`
function completes. It contains `event.responseCode`, `event.productId`, `event.productType` and
`event.developerPayload` fields.<h3># Event.RESTORE_TRANSACTIONS_COMPLETE</h3>Dispatched
when `restoreTransactions` function completes. It contains `event.responseCode` fields.<h3>#
Event.CONFIRM_NOTIFICATION_COMPLETE</h3>Dispatched when `confirmNotification` function
completes. It contains `event.responseCode` and `event.notificationId` fields.<h3>#
Event.PURCHASE_STATE_CHANGE</h3>Dispatched when information about a transaction is received. It
contains `event.purchaseState`, `event.productId`, `event.notificationId`, `event.purchaseTime` and
`event.developerPayload` fields.

GoogleBilling : checkBillingSupported 2012.09+


This request verifies that the Google Play application supports in-app billing.You usually send this request
when your application first starts up. This request isuseful if you want to enable or disable certain UI features
that are relevant only toin-app billing.
bool = GoogleBilling:checkBillingSupported(productType)

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.

GoogleBilling : confirmNotification 2012.09+

Gideros API Reference v2017.12 Page 228


This request acknowledges that your application received the details of a purchase state change.
bool = GoogleBilling:confirmNotification(notificationId)

Parameter:
notificationId : (str)

Result:
bool : `true` if in-app billing service is available, `false` otherwise.

GoogleBilling : requestPurchase 2012.09+


This request sends a purchase message to the Google Play application and is the foundation of in-app
billing.You send this request when a user indicates that he or she wants to purchase an item in your
application.Google Play then handles the financial transaction by displaying the checkout user interface.
bool = GoogleBilling:requestPurchase(productId, productType, developerPayload)

Parameters:
productId : (str)
productType : (string, optional)
developerPayload : (string, optional)

Result:
bool : `true` if in-app billing service is available, `false` otherwise.

GoogleBilling : restoreTransactions 2012.09+


This request retrieves a user's transaction status for managed purchases. You should send this message
only when you need toretrieve a user's transaction status, which is usually only when your application is
reinstalled or installed for the first time on a device.
bool = GoogleBilling:restoreTransactions()
bool : `true` if in-app billing service is available, `false` otherwise.

GoogleBilling : setApiVersion 2012.09+


Sets the API version. You can find more information
http://developer.android.com/guide/google/play/billing/billing_reference.html#billing-versions
GoogleBilling:setApiVersion(apiVersion)
apiVersion : (num)

GoogleBilling : setPublicKey 2012.09+


Sets the public key. You can find the public key portion of this key pair on your Google Play account's profile
page.
GoogleBilling:setPublicKey(publicKey)
publicKey : (str) Your Google Play public key

Gideros API Reference v2017.12 Page 229


iad 2012.8+
iAd module for iOS allows you to use iAd framework that was introduced in iOS 4.0. To load the iAd module,
call `require 'iad'`. After loading iAd module, `iad` table stores all classes and functions related to iAd
framework.

iad . isAvailable 2012.8+


Returns `true` if iAd framework is available for this platform, `false` otherwise. For iOS 4.0 , this function
returns `true`.
bool = iad.isAvailable()
bool : `true` if iAd framework is available for this platform, `false` otherwise

Gideros API Reference v2017.12 Page 230


iad.Banner Inherits: EventDispatcher 2012.8+
The `iad.Banner` class provides a view that displays banner advertisements to the user. When the user taps
a banner view, the view triggers an action programmed into the advertisement. For example, an
advertisement might show a movie, present a modal advertisement, or launch Safari to show a
webpage.Your application is notified when an action starts and stops, but does not otherwise interact with
the advertisement.

iad . Banner . new 2012.8+


Creates an `iad.Banner` instance. If iAd framework is not available, this function gives an error.The
alignment and the orientation of the ad banner are defined by these 4 string
constants:<ul><li>`iad.Banner.TOP = 'top'`</li><li>`iad.Banner.BOTTOM =
'bottom'`</li><li>`iad.Banner.PORTRAIT = 'portrait'`</li><li>`iad.Banner.LANDSCAPE =
'landscape'`</li></ul>And `iad.Banner` class dispatches these 4
events:<ul><li>`Event.BANNER_AD_LOADED = 'bannerAdLoaded'`</li><li>`Event.BANNER_AD_FAILED
= 'bannerAdFailed'`</li><li>`Event.BANNER_ACTION_BEGIN =
'bannerActionBegin'`</li><li>`Event.BANNER_ACTION_FINISHED =
'bannerActionFinished'`</li></ul>When an ad banner is created, iAd will start requesting ads. Apple serves
ads, and refreshes with new ads, on an automatic timer.Apple also requires that the ad area be hidden when
no ad is available to display. iAd module manages all this behavior for you automatically.When an ad
becomes available, it will be displayed on the screen, the event `Event.BANNER_AD_LOADED` is
dispatched when one is about to be displayed,or the event `Event.BANNER_AD_FAILED` is dispatched
when the loading has failed. If the loading has failed, the fields `event.errorCode` and `event.errorDescription`
contains information about the failure reason.When the user clicks on an ad, the event
`Event.BANNER_ACTION_BEGIN` is dispatched. At this time, the user will either be taken out of your
application to view the app store (in this case `event.willLeaveApplication` field will be true), or they will be
presented with a fullscreen advertisement to interact with, and `event.willLeaveApplication` will be false. In
the latter case, you may decide to pause the application until the event
`Event.BANNER_ACTION_FINISHED` is dispatched.
iad.Banner.new(alignment, orientation)
alignment : (str) whether you want ads to show top or bottom of the screen. It can be either iad.Banner.TOP
or iad.Banner.BOTTOM.
orientation : (str) orientation of the banner. It can be either iad.Banner.PORTRAIT or
iad.Banner.LANDSCAPE.

Example:
-- if the platform is iOS, load the iAd module
if application:getDeviceInfo() == 'iOS' then
require 'iad'
end

-- 4 event listeners for debug print


local function onBannerAdLoaded()
print('banner ad loaded')
end

local function onBannerAdFailed(event)


print('banner ad failed', event.errorCode, event.errorDescription)
end

local function onBannerActionBegin(event)

Gideros API Reference v2017.12 Page 231


print('banner action begin', event.willLeaveApplication)
end

local function onBannerActionFinished()


print('banner action finished')
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

-- show the banner (if it exists)


function showBanner()
if banner ~= nil then
banner:show()
end
end

-- hide the banner (if it exists)


function hideBanner()
if banner ~= nil then
banner:hide()
end
end

iad . Banner : hide 2012.8+


Hides the ad banner.
iad.Banner:hide()

iad . Banner : isBannerLoaded 2012.8+


Returns `true` if the ad banner has downloaded an advertisement, `false` otherwise.
bool = iad.Banner:isBannerLoaded()
bool : `true` if the ad banner has downloaded an advertisement, `false` otherwise

iad . Banner : setAlignment 2012.8+


Sets the alignment of the banner as the top or bottom.
iad.Banner:setAlignment(alignment)
alignment : (str) whether you want ads to show top or bottom of the screen. It can be either iad.Banner.TOP
or iad.Banner.BOTTOM.

Gideros API Reference v2017.12 Page 232


iad . Banner : show 2012.8+
Shows the ad banner if an ad is currently available or when an ad becomes available.
iad.Banner:show()

Gideros API Reference v2017.12 Page 233


json 2013.09+
Provides Lua table serialization and deserialization to and from string in json format

json . decode 2013.09+


Returns Lua table from provided json encoded string
json.decode(jsondata)
jsondata : (str) Data in json format which to deserialize to Lua table

json . encode 2013.09+


Returns encoded json string from provided Lua table
json.encode(data)
data : (table) Lua table which to serialize to json

Gideros API Reference v2017.12 Page 234


lfs 2012.8+
LFS or LuaFileSystem is a Lua library developed to complement the set of functions related to file systems
offered by the standard Lua distribution.LuaFileSystem offers a portable way to access the underlying
directory structure and file attributes.For more information and detailed documentation, please visit
[http://keplerproject.github.io/luafilesystem/manual.html#reference](http://keplerproject.github.io/luafilesystem/
manual.html#reference).

Gideros API Reference v2017.12 Page 235


lpeg 2012.8+
LPeg is a pattern-matching library for Lua, based on Parsing Expression Grammars (PEGs).For more
information and detailed documentation, please visit
[http://www.inf.puc-rio.br/~roberto/lpeg/](http://www.inf.puc-rio.br/~roberto/lpeg/)

Gideros API Reference v2017.12 Page 236


Microphone 2013.06+
Use this plugin to record to an audio clip using a connected microphone.

Microphone . new 2013.06+


Creates a new Microphone object.
Microphone.new(deviceName, sampleRate, numChannels, bitsPerSample)
deviceName : (str) The name of the device. Passing nil or an empty string will pick the default device.
sampleRate : (num) Sample rate of the recording. This value should be between 4000 and 44100.
numChannels : (num) Number of channels. This value can be 1 for mono and 2 for stereo.
bitsPerSample : (num) Bits per sample. This value can be 8 or 16.

Microphone : setOutputFile 2013.06+


Sets the output file. If an output file is specified, captured audio is recorded to this file. You cannot set output
file while recording.
Microphone:setOutputFile(fileName)
fileName : (str) The filename. It should be on documents or temporary directory.

Microphone : start 2013.06+


Start recording with device.
Microphone:start()

Microphone : stop 2013.06+


Stop recording.
Microphone:stop()

Gideros API Reference v2017.12 Page 237


Notification 2011.6+
Notification class is used to compose and schedule new local notifications. You need to provide an ID of
notification to constructor. Using same provided ID you can create a new instance of Notification class and
modify existing notification with that ID. Additionally the ID allows you to identify local notification in the table
of scheduled local notifications retrieved from `NotificationManager:getScheduledNotifications`, or table of
local notifications that were already displayed using `NotificationManager:getLocalNotifications``Notification`
consists of notification message, title, sound and number. Only message is the mandatory one. You can
combine others as you wish.

Create new notification and dispatch right away


local note=Notification.new(1)
note:setTitle("Notification app")
note:setMessage("Do you see me?")
note:setSound("./some_sound.wav")
note:dispatchNow()

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

Create new notification and dispatch on specific date in specific time


local note=Notification.new(3)
note:setTitle("Notification app")
note:setMessage("Happy Birthday")
note:dispatchOn({year=2013, month=8, day=1, hour=9, min=0, sec=0})

Modifying existing scheduled notification


--id of notification to modify
local id=1

--retrieve shared instance


local mngr=NotificationManager.getSharedInstance()

--retrieve table with scheduled notifications


local t=mngr:getScheduledNotifications()

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

Notification . new 2011.6+


Creates new notification object with provided id. Scheduled notifications can later be canceled or modified

Gideros API Reference v2017.12 Page 238


using provided ID.Here are couple of scenarios that may happen, when creating notifications:Notification with
provided ID does not exist yet, so you simply create new scheduled notification.Next if you create another
notification with same ID, while the first one is till scheduled, you will simply modify the existing scheduled
notification with new title, message, etc and can even change it's scheduled time by redispatching it.If you
create notification with same ID, while the first notification was already displayed, you will simply create a new
notification.So as you see, you may use notification ID's as types of notifications. For example, if you have a
energy bar that will be restored after some time, you could always dispatch this notification with same
ID.However, if you want to display for example, that there are new chat messages from different users, they
should have different IDs.
Notification.new()

Notification : cancel 2011.6+


Cancels previously scheduled, but not yet displayed notification
Notification:cancel()

Notification : dispatchAfter 2011.6+


Dispatches notification after provided period of time. Optionally can provide repeat time interval, in which
notification should be repeated until canceled.Both dispatch after period of time and repeating time format is
similar to os.date("*t") retrieved format. As in you can provide time as table with these options as keys: sec -
for secondsmin - for minuteshour - for hoursday - for day of the monthmonth - for monthyear - for year
Notification:dispatchAfter()

Notification : dispatchNow 2011.6+


Dispatches notification right away. Note that based on app settings, user might not be able to see the
notification dispatched when you app is opened, but it will still be available in the devices list of dispatched
notifications
Notification:dispatchNow()

Notification : dispatchOn 2011.6+


Dispatches notification on provided date in device's timezone. Optionally you can provide repeat time interval,
in which notification should be repeated until canceled.Both dispatch date and repeating time format is similar
to os.date("*t") retrieved format. As in you can provide date as table with these options as keys: sec - for
secondsmin - for minuteshour - for hoursday - for day of the monthmonth - for monthyear - for year
Notification:dispatchOn()

Notification : getId 2011.6+


Returns user assigned ID of local notification
Notification:getId()

Notification : getMessage 2011.6+


Retrieves the message of local notification that was previously set.
Notification:getMessage()

Gideros API Reference v2017.12 Page 239


Notification : getNumber 2011.6+
Retrieves the number of local notification that was previously set.
Notification:getNumber()

Notification : getSound 2011.6+


Retrieves the sound of local notification that was previously set.
Notification:getSound()

Notification : getTitle 2011.6+


Retrieves the title of local notification that was previously set.
Notification:getTitle()

Notification : setNumber 2011.6+


Sets the number of local notification. Usually number is used to represent amount of events awaiting for user,
as amount of unreplied messages, etc. By default number is 0 and is not shown.On Android number in local
notifications is visible only starting from Android 3.0 version (but can be provided in any version).On IOS
number is represented as a badge number at your application icon.
Notification:setNumber()

Notification : setSound 2011.6+


Sets the sound which is played when notification is shown.By default no sound is played and if you want to
play default system sound, then you can use `Notification.DEFAULT_SOUND` constantFor cross-platform
compatability it is better to use .wav file types.For IOS the audio length can not exceed 30 secondsYou can
reference this <a
href='https://developer.apple.com/library/IOs/documentation/NetworkingInternet/Conceptual/RemoteNotificati
onsPG/Chapters/IPhoneOSClientImp.html' target='_blank'>IOS notification guide</a> for converting sound to
needed formats on IOS.
Notification:setSound()

Notification : setTitle 2011.6+


Sets the title text of local notification, usually used as app name.On Android title is displayed as ticker text
and title inside local notification.On IOS title represents the action on slide bar.
Notification:setTitle()

Gideros API Reference v2017.12 Page 240


NotificationManager Inherits: EventDispatcher 2011.6+
NotificationManager is the class that allows you to manage scheduled and received notifications. This is a
class with a single instance which can be retrieved using getSharedInstance() and can not have any new
instances.With NotificationManager you can retrieve information about all scheduled local notifications, all
received local notifications and all received push notifications. As well as clear all type of notifications and
cancel scheduled notifications.NotificationManager instance also receives events about notification being
clicked and app opened through that specific notification. As well as registration for push notification event or
registration error.

Modifying existing scheduled notification


--id of notification to modify
local id=1

--retrieve shared instance


local mngr=NotificationManager.getSharedInstance()

--retrieve table with scheduled notifications


local t=mngr:getScheduledNotifications()

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

Checking if notification is stil scheduled


--id of notification to check
local id=1

--retrieve shared instance


local mngr=NotificationManager.getSharedInstance()

--retrieve table with scheduled notifications


local t=mngr:getScheduledNotifications()

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

Gideros API Reference v2017.12 Page 241


--printing other information
print("Title: "..e.title)
print("Text: "..e.message)
print("Number: "..e.number)
end)

Registering for push notifications


--retrieve shared instance
local mngr=NotificationManager.getSharedInstance()

--if registration completed succesfully


mngr:addEventListener(Event.PUSH_REGISTRATION, function(e)
--getting device token
local token=e.deviceToken

--sending token to your server


local loader=UrlLoader.new("http://yourdomain.com/register.php?token="..token)
loader:addEventListener(Event.COMPLETE, function()
--token succesfuly deliverd
end)
end)

--if registration failed


mngr:addEventListener(Event.PUSH_REGISTRATION_ERROR, function(e)
--device could not been registered now
--try again later
print(e.error)
end)

--try to register for push notifications


mngr:registerForPushNotifications("953841987672")

NotificationManager . getSharedInstance 2011.6+


Returns the shared instance of NotificationManager class. There can be no other instance.
NotificationManager.getSharedInstance()

NotificationManager : cancelAllNotifications 2011.6+


Cancels all currently scheduled but not yet displayed local notifications.
NotificationManager:cancelAllNotifications()

NotificationManager : cancelNotification 2011.6+


Cancel specific scheduled notification by it's ID.Basically it's the same as creating new notification with same
ID and cancelling it:
NotificationManager:cancelNotification()

Cancel notification

Gideros API Reference v2017.12 Page 242


--id of notification to cancel
local id=1

--cancel through notification isntance


local notification=Notification.new(id)
notification:cancel()

--cancel through NotificationManager


local mngr=NotificationManager:getSharedInstance()
mngr:cancelNotification(id)

NotificationManager : clearLocalNotifications 2011.6+


Clears the data about already displayed local notifications that can be retrieved using
`NotificationManager:getLocalNotifications` method.
NotificationManager:clearLocalNotifications()

NotificationManager : clearPushNotifications 2011.6+


Clears the data about received push notifications that can be retrieved using
`NotificationManager:getPushNotifications` method.
NotificationManager:clearPushNotifications()

NotificationManager : getLocalNotifications 2011.6+


Retrieves the lua table of already displayed local notifications. The table uses notification ids as keys and
table with information about notification as value.
NotificationManager:getLocalNotifications()

Here is an example structure of returned table:


Table {
[2] => Table {
{
[message] => Do you see me?
[title] => Test from Server1
[id] => 2
[number] => 0
[sound] => "somesound.wav"
}
[10] => Table {
{
[message] => Do you see me?
[title] => Test from Server2
[id] => 10
[number] => 0
[sound] => ""
}
}

NotificationManager : getPushNotifications 2011.6+

Gideros API Reference v2017.12 Page 243


Retrieves the lua table of received push notifications. On Android all pushed notifications appear here, but on
IOS only pushed notifications that user clicked on or that were received while application was in foreground
appear here.You must provide an ID on the server to identify your push notification in this list.
NotificationManager:getPushNotifications()

Here is an example structure of returned table:


Table {
[2] => Table {
{
[message] => Do you see me?
[title] => Test from Server1
[id] => 2
[number] => 0
[sound] => "somesound.wav"
}
[10] => Table {
{
[message] => Do you see me?
[title] => Test from Server2
[id] => 10
[number] => 0
[sound] => ""
}
}

NotificationManager : getScheduledNotifications 2011.6+


Retrieves the lua table of scheduled local notifications, that were not yet displayed. The table uses notification
ids as keys and table with information about notification as value.
NotificationManager:getScheduledNotifications()

Here is an example structure of returned table:


Table {
[2] => Table {
{
[message] => Do you see me?
[title] => Test from Server1
[id] => 2
[number] => 0
[sound] => "somesound.wav"
}
[10] => Table {
{
[message] => Do you see me?
[title] => Test from Server2
[id] => 10
[number] => 0
[sound] => ""
}
}

Gideros API Reference v2017.12 Page 244


NotificationManager : registerForPushNotifications 2011.6+
Register device for receiveng push notifications.On Android this method accepts the string value of project ID
in Google API console.On IOS this method does not require any input, but for compatability purpose, you
may pass same string as for Android or any other string, as it won't do any harm.Before calling this method
you should register for two events: for successful registration for registration errorUpon successful
registration you will receive the device token with the event object, that you should pass to your server, which
will be sending push notifications.Although this method can be called multiple times, and even if already
registered it will still return same device token with the event object, but it is still recommended to persistant
store device token if you'll be needing it later.
NotificationManager:registerForPushNotifications()

Registering for push notifications


--retrieve shared instance
local mngr=NotificationManager.getSharedInstance()

--if registration completed succesfully


mngr:addEventListener(Event.PUSH_REGISTRATION, function(e)
--getting device token
local token=e.deviceToken

--sending token to your server


local loader=UrlLoader.new("http://yourdomain.com/register.php?token="..token)
loader:addEventListener(Event.COMPLETE, function()
--token succesfuly deliverd
end)
end)

--if registration failed


mngr:addEventListener(Event.PUSH_REGISTRATION_ERROR, function(e)
--device could not been registered now
--try again later
print(e.error)
end)

--try to register for push notifications


mngr:registerForPushNotifications("953841987672")

NotificationManager : unregisterForPushNotifications 2011.6+


Unregister device from receiving push notifications. Basically this method invalidates the deviceToken. You
still need to remove the token from your server by yourself, or else using invalidated tokens may lead to
errors in some push notification services.
NotificationManager:unregisterForPushNotifications()

Gideros API Reference v2017.12 Page 245


sqlite3 2012.2.1+
Gideros runtime supports public domain SQLite3 database engine for iOS, Android and Desktop platforms.
For more information and detailed documentation, please visit
[http://lua.sqlite.org](http://lua.sqlite.org).<h3>SQLite3 on Android platforms</h3>Currently, LuaSQLite3
plugin cannot open databases stored in APK files. Therefore, database file should becopied from resource
directory to documents directory.To copy a file, this function can be used:<pre><code>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 dolocal block = srcf:read(size)if not block then break
enddstf:write(block)end srcf:close()dstf:close()end</code></pre>Also it's better to check if the
database file is previously copied or not. To check if a file can be found on the underlying file system, this
function can be used:<pre><code>local function exists(file)local f = io.open(file, 'rb')if f == nil
thenreturn falseendf:close()return trueend</code></pre>By using these two function, you can
copy the database file from resource to documents directory before using it:<pre><code>if not
exists('|D|database.db') thencopy('database.db', '|D|database.db')end</code></pre><h3>SQLite3 on on
WinRT need to add an extension to Visual Studio</h3>Gideros now supports sqlite and to make this work on
Windows Phone, it is necessary to add an extension to Visual Studio. Even if you don't use sqlite, you will
need to add this extension or Windows Phone projects exported by Gideros will not compile. It's easy to do
as explained next. Of course, you only need to add the extension once. <br/>Open Visual Studio and go to
`TOOLS > Extensions and Updates`. Select the `Online` tab on the left and type sqlite in the search bar at the
top right. Select `SQLite` for Windows 8.1 or/and Windows Phone 8.1 and select install. You will need to
restart VS for the extension to take effect.

Gideros API Reference v2017.12 Page 246


StoreKit 2012.2.2+
The `StoreKit` class provides the functionality that allow an application to request payment from a user. This
class is only available to iOS platforms.The `StoreKit` class is defined in module 'storekit'. Therefore, you
need to call`require('storekit')` before using it. Loading the 'storekit' module also creates a global variable
`storekit` of type `StoreKit` for direct use. <h3>State of a Transaction</h3>The state of a transaction is
defined by 3 string constants:<ul><li>**StoreKit.PURCHASED = 'purchased'**: The App Store successfully
processed payment. Your application should provide the content the user
purchased.</li><li>**StoreKit.FAILED = 'failed'**: The transaction failed. Check the `event.errorCode` and
`event.errorDescription` fields to determine what happened.</li><li>**StoreKit.RESTORED = 'restored'**:
This transaction restores content previously purchased by the user. Read the `event.originalTransaction` field
to obtain information about the original purchase.</li></ul><h3>StoreKit Events</h3>The `StoreKit` class
dispatches the events `Event.REQUEST_PRODUCTS_COMPLETE`, `Event.TRANSACTION` and
`Event.RESTORE_TRANSACTIONS_COMPLETE`.<h3>#
Event.REQUEST_PRODUCTS_COMPLETE</h3>The function [[StoreKit:requestProducts]] is used to
retrieve localized information about a list of products from the Apple App Store. When the request completes,
`Event.REQUEST_PRODUCTS_COMPLETE` event is dispatched. The resulting event table contains these
additional fields about the products:<ul><li>**event.error:** (number) error code if the request failed to
execute</li><li>**event.errorDescription:** (string) error description if the request failed to
execute</li><li>**event.products:** (table) array of products where each element is a table which contains
the product information</li><li>**event.invalidProductIdentifiers:** (table) array of product identifier strings
that were not recognized by the Apple App Store</li></ul>Each table in `event.products` array contains
these fields:<ul><li>**title:** (number) localized name of the product</li><li>**description:** (string)
localized description of the product</li><li>**price:** (number) cost of the product in the local
currency</li><li>**productIdentifier:** (string) string that identifies the product to the Apple App
Store</li></ul>For example, this code can be used to print the retrieved product
information:<pre><code>local function onRequestProductsComplete(event)if event.errorCode ~= nil
thenprint('error', event.errorCode, event.errorDescription)returnendprint('products:')for
i=1,#event.products doprint('title', event.products[i].title)print('description',
event.products[i].description)print('price', event.products[i].price)print('productIdentifier',
event.products[i].productIdentifier)endprint('invalidProductIdentifiers:')for
i=1,#event.invalidProductIdentifiers
doprint(event.invalidProductIdentifiers[i])endend</code></pre><h3>#
Event.TRANSACTION</h3>This event is dispatched when a transaction is updated. The event listener
should process all successful transactions, unlock the functionality purchased by the user, and then finish
the transaction by calling [[StoreKit:finishTransaction]] method. The resulting event table can contain these
additional fields about the products:<ul><li>**event.errorCode:** (number) error code if
`event.transaction.state` is set to `StoreKit.FAILED`</li><li>**event.errorDescription:** (string) error
description if `event.transaction.state` is set to `StoreKit.FAILED`</li><li>**event.payment.productIdentifier:**
(string) product identifier of the transaction</li><li>**event.payment.quantity:** (number) number of items the
user wants to purchase</li><li>**event.transaction.state:** (string) current state of the
transaction</li><li>**event.transaction.identifier:** (string) string that uniquely identifies a successful payment
transaction</li><li>**event.transaction.receipt:** (string) signed receipt that records all information about a
successful payment transaction</li><li>**event.transaction.date:** (string) date the transaction was added to
the App Store's payment queue</li><li>**event.originalTransaction.identifier:** (string) identifier of original
transaction</li><li>**event.originalTransaction.date:** (string) date of the original transaction</li></ul>This
code can be used to print the transaction information and unlock the functionality purchased by the
user:<pre><code>local function onTransaction(event)print('payment.productIdentifier',
event.payment.productIdentifier)print('payment.quantity',
event.payment.quantity)print('transaction.state', event.transaction.state)if event.transaction.state ==
StoreKit.FAILED thenprint('error', event.errorCode,
event.errorDescription)elseprint('transaction.identifier',
event.transaction.identifier)print('transaction.date', event.transaction.date)if event.transaction.state ==

Gideros API Reference v2017.12 Page 247


StoreKit.PURCHASED thenprint('transaction.receipt', event.transaction.receipt)endif
event.transaction.state == StoreKit.RESTORED thenprint('originalTransaction.identifier',
event.originalTransaction.identifier)print('originalTransaction.date',
event.originalTransaction.date)end-- unlock the functionality purchased by the
userendstorekit:finishTransaction(event.transaction)end</code></pre><h3>#
Event.RESTORE_TRANSACTIONS_COMPLETE</h3>This event is dispatched after the transactions are
delivered. The resulting event table can contain these additional fields:<ul><li>**event.errorCode:**
(number) error code if an error occurred while restoring transactions</li><li>**event.errorDescription:**
(string) description of the error if an error occurred while restoring transactions</li></ul>If all transactions
are delivered successfully, `event.errorCode` and `event.errorDescription` will be `nil`.

StoreKit : canMakePayments 2012.2.2+


Returns whether the user is allowed to make payments.
bool = StoreKit:canMakePayments()
bool : `true` if the user is allowed to authorize payment. `false` if they do not have permission.

StoreKit : finishTransaction 2012.2.2+


Completes a pending transaction. Your application should call this function only after it has successfully
processed the transaction and unlocked the functionality purchased by the user.
StoreKit:finishTransaction(transaction)
transaction : (table) transaction information recevied with the event Event.TRANSACTION.

StoreKit : purchase 2012.2.2+


Process a payment request. When that transaction is complete or if a failure occurs, `Event.TRANSACTION`
event is dispatched.
StoreKit:purchase(productIdentifier, quantity)
productIdentifier : (str) A string used to identify a product that can be purchased from within your application.
quantity : (number, default = 1) The number of items the user wants to purchase. This value should be greater
than or equal to 1.

StoreKit : requestProducts 2012.2.2+


Retrieve localized information about a list of products from the Apple App Store. When the request
completes, `Event.REQUEST_PRODUCTS_COMPLETE` event is dispatched.
StoreKit:requestProducts(productIdentifiers)
productIdentifiers : (table) An array of product identifiers for the products you wish to retrieve descriptions of.

StoreKit : restoreCompletedTransactions 2012.2.2+


Restore previously completed purchases. `Event.TRANSACTION` event is dispatched for each previously
completed transaction that can be restored. Each transaction includes a copy of the original
transaction.After the transactions are delivered, `Event.RESTORE_TRANSACTIONS_COMPLETE` event is
dispatched. If an error occurred while restoring transactions, `event.errorCode` and `event.errorDescription`
fields contain the details of the error.
StoreKit:restoreCompletedTransactions()

Gideros API Reference v2017.12 Page 248

Potrebbero piacerti anche