Está en la página 1de 18

REFERENTE A LUA

PALABRAS RESERVADAS
and

break

for
or

do

else

function
repeat

if
return

elseif
in
then

end
local
true

false
nil
until

not
while

SIMBOLOS RESERVADOS
+

==
(
;

*
~=
)
:

/
<=
{
,

%
>=
}
.

^
<
[
..

#
>
]
...

TABLAS
t = {}
k = "x"
t[k] = 3.14
print( t[k] )
print( t["x"] )
print( t.x )
t[2] = "foo"
print( t[2] )

--create a table
--new table entry, with key="x" and value=3.14
--> 3.14
--> 3.14
--> 3.14
--new table entry, with key=2 and value="foo"
--> "foo"

Campos de tabla
t = { foo="hello" }
print( t.foo )

--create table with a single property "foo"


--> "hello"

t.foo = "bye"
print( t.foo )

--assign a new value to property "foo"


--> "bye"

t.bar = 10
print( t.bar )
print( t["bar"] )

--create a new property named "bar"


--> 10
--> 10

VARIABLE GLOBAL (solo si es necesario)


print( s ) --> nil
s = "One million dollars"
print( s ) --> One million dollars

VARIABLE LOCAL (recomendado)


local y = 10

--local variable

OPERADORES ARITMETICOS
+

(addition)
* (multiplication)
% (modulo)

(subtraction)
/ (division)
^ (exponentiation)

OERADORES RELACIONALES
==
~=
<
>
<=
>=

(equal to)
(not equal to)
(less than)
(greater than)
(less than or equal to)
(greater than or equal to)

OPERADORES LOGICOS
and, or, not

LONGITUD DE OPERADOR
Anteponer (#)

+ sintaxis for
for i=1,#nombretabla
--instrucciones
end

do

FUNCIONES
Funcin local
local function f ()
--body
end

Funcin global
function f ()
--body
end

local f = function()
--body
end

f = function ()
--body
end

BORRAR UN OBJETO DE LA PANTALLA


myObject:removeSelf()
--OR...
display.remove ( myObject )
myObject = nil

SINTAXIS IF

SINTAXIS SWITCH

if (condicion) then
--Instrucciones
else
--Instrucciones

if (condicion) then
--Instrucciones
elseif (condicion)
--Instrucciones
end
--Asi cuantos elseif se requieran

end

REFERENTE A CORONA
IMPRIMIR HELLO WORLD EN CONSOLA
print( "Hello World!" )

MOSTRAR HELLO WORLD EN PANTALLA


SINTAXIS: display.newText( string, x, y, font, size )
EJEMPLO: local myTextObject = display.newText( "Hello World!", 160, 240,
"Arial", 60 )
METODO PARA PONERLE COLOR
myTextObject:setFillColor( r, g, b )
APLICANDO FUNCION,
--para que el texto en pantalla cambie de color aleatoriamente
function screenTap()
local r = math.random( 0, 100 )
local g = math.random( 0, 100 )
local b = math.random( 0, 100 )
myTextObject:setFillColor( r/100, g/100, b/100 )
end
--agregando listener (oyente, escuhador) para que cada vez que se hace click
--en el mismo punto se cambie de color el tecto en pantalla
display.currentStage:addEventListener( "tap", screenTap )
--Es el equivalente a esto (listener global)
Runtime:addEventListener("tap", screenTap)
--tambin se puede poner un listener solo para mostrar el cambio de color
--cuando solo se toca el texto en pantalla
myTextObject:addEventListener("tap", screenTap)

FISICA (bsica)
local physics = require( "physics" )
physics.start()

OBJETOS VISUALES
newImage: forma 1
SINTAXIS: display.newImage( "ruta",x,y )
local sky = display.newImage( "bkg_clouds.png" )
sky.x = 160; sky.y = 195 -- (propiedades del objeto para cambiar su posicion)

newImage: forma 2
local sky = display.newImage( "bkg_clouds.png",160,195 )

Agregando fsica al cuerpo del objeto


physics.addBody(sky, "static", { density=3.0, friction=0.5, bounce=0.3 } )

OPTIMIZACION

Apagar gps, wifi, acelermetro, etc porque consumen la batera


Usar memoria potencia de 2 cuando se usan graficos, el comando
system.getInfo()te permite saber los datos del dispositivo
Para lua es mejor usar
Ubicacin, usar variable local CCX
--NON-LOCAL (DISCOURAGED = no
recomendado)
CCX = display.contentCenterX
--global variable
for i = 1,100 do
local image = display.newImage(
"myImage" )
image.x = CCX
end

--LOCAL (RECOMMENDED)
local CCX = display.contentCenterX
--local variable
for i = 1,100 do
local image = display.newImage(
"myImage" )
image.x = CCX
end

tambien aplica a la librera matemtica


--NON-LOCAL (DISCOURAGED)
CCX = display.contentCenterX
--global variable
for i = 1,100 do
local image = display.newImage(
"myImage" )
image.x = CCX
end

--"EXTERNAL" LOCAL (RECOMMENDED)


local sin = math.sin --local
reference to 'math.sin'
local function foo(x)
for i = 1,100 do
x = x + sin(i)
end
return x
end

y a funciones; ver orden de creacin de funciones tambin


--NON-LOCAL (DISCOURAGED)
function func1()
func2( "myValue" )
end
function func2( y )
print( y )
end

--LOCAL (RECOMMENDED)
local function func2( y ) --'func2'
properly scoped above 'func1'
print( y )
end
local function func1()
func2( "myValue" )
end

func1()
func1()

Para poner elementos en las tablas evitar table.insert()


--table.insert() (DISCOURAGED)

--LOOP INDEX METHOD (RECOMMENDED)

local a = {}
local table_insert = table.insert
for i = 1,100 do
table_insert( a, i )
end
--TABLE SIZE METHOD (ACCEPTABLE)
local a = {}
for i = 1,100 do
a[#a+1] = i
end

local a = {}
for i = 1,100 do
a[i] = i
end

--COUNTER METHOD (RECOMMENDED)


local a = {}
local index = 1
for i = 1,100 do
a[index] = i
index = index+1
end

Para sacar elementos de las tablas evitar table.unpack()


--unpack() (DISCOURAGED)
local a = { 100, 200, 300, 400 }

--LOOP METHOD (RECOMMENDED)


local a = { 100, 200, 300, 400 }

for i = 1,100 do
print( unpack(a) )
end

for i = 1,100 do
print( a[1],a[2],a[3],a[4] )
end

Evitar "ipairs()"
--ipairs() (DISCOURAGED)
local t1 = {}
local t2 = {}
local t3 = {}
local t4 = {}
local a = { t1, t2, t3, t4 }

--LUA
local
local
local
local
local

CONSTRUCT (RECOMMENDED)
t1 = {}
t2 = {}
t3 = {}
t4 = {}
a = { t1, t2, t3, t4 }

for i,v in ipairs( a ) do


print( i,v )
end

for i = 1,#a do
print( a[i] )
end

Mejoramiento de la matemtica
--DIVISION (DISCOURAGED)
x/2 ; y/8

--MULTIPLICATION BY DECIMAL
(RECOMMENDED)
x * 0.5 ; y * 0.125

--EXPONENTIATION (DISCOURAGED)
x^3

--MULTIPLICATION (RECOMMENDED)
x * x * x

Tambien en el resto por divisin inexacta


--math.fmod() (DISCOURAGED)
local fmod = math.fmod
for i = 1,100 do
if ( fmod( i,30 ) < 1 ) then

--MODULUS OPERATOR (RECOMMENDED)


for i = 1,100 do
if ( ( i%30 ) < 1 ) then
local x = 1

local x = 1
end
end

end
end

ADMINISTRACION DE AUDIO
Para sonidos cortos usar loadSound
local soundTable = {
mySound1 = audio.loadSound(
mySound2 = audio.loadSound(
mySound3 = audio.loadSound(
mySound4 = audio.loadSound(
mySound5 = audio.loadSound(
mySound6 = audio.loadSound(
mySound7 = audio.loadSound(
mySound8 = audio.loadSound(
}

"a.wav"
"b.wav"
"c.wav"
"d.wav"
"e.wav"
"f.wav"
"g.wav"
"h.wav"

),
),
),
),
),
),
),
),

--Y luego los llamas


local mySound = audio.play( soundTable["mySound1"] )
--y para mejorar el rendimiento de liberacin de memoria se elimina asi
local ST = soundTable
for s=#ST,1,-1 do
audio.dispose( ST[s] ) ; ST[s] = nil
end

GRAFICOS, AUDIO Y ANIMACION


* significa que hay mas documentacin
Sintaxis
Tanto x, y representan posicin

Ejemplo

display.newGroup()

local rect = display.newRect(0, 0, 100, 100)


rect:setFillColor( 0.5 )
local group = display.newGroup()
group:insert( rect )

display.newImage( [parent,] filename


[,baseDir] [,x,y] [,isFullResolution])

local myImage = display.newImage( "image.png" )


--algunos mtodos (aplica para todos los objetos)
-- position the image
myImage:translate( 100, 100 )
-- tint the image red
myImage:setFillColor( 1, 0, 0 )
-- remove the image

myImage:removeSelf()
myImage = nil
--algunas propiedades (aplica para todos los objetos)
-- hide the image
myImage.isVisible = false
display.newImage( [parent,]
imageSheet, frameIndex )

-- first, create the image sheet object


local options =
{
-- The params below are required
width = 70,
height = 41,
numFrames = 2,
-- The params below are optional (used for dynamic
image sheet selection)
sheetContentWidth = 70,
of entire sheet
sheetContentHeight = 82
size of entire sheet
}

-- width of original 1x size


-- height of original 1x

local imageSheet = graphics.newImageSheet( "fishies.png",


options )
local myImage = display.newImage( imageSheet, 1 )
display.newImageRect( [parentGroup,]
filename, [baseDir,] width, height )

local image = display.newImageRect( "image.png", 100, 100


)
--algunas propiedades (aplica para todos los objetos)
image.x = display.contentCenterX
image.y = display.contentCenterY
-- hide the object
image.isVisible = false
--algunos mtodos (aplica para todos los objetos)
-- remove it
image:removeSelf()
image = nil

display.newImageRect( [parentGroup,]
imageSheet, frameIndex, width,
height )

-- first, create the image sheet object


local options =
{
-- The params below are required
width = 70,
height = 41,
numFrames = 2,

-- The params below are optional (used for dynamic


image sheet selection)
sheetContentWidth = 70,
of entire sheet
sheetContentHeight = 82
size of entire sheet
}

-- width of original 1x size


-- height of original 1x

local imageSheet = graphics.newImageSheet( "fishies.png",


options )
-- create new image from the above image sheet
local obj = display.newImageRect( imageSheet, 1, 70, 41 )
obj.x, obj.y = 100, 100
display.newText( [parentGroup,] text,
x, y, font, fontSize )
display.newText( [parentGroup,] text,
x, y, [width, height,] font,
fontSize )

*
local myText = display.newText( "Hello World!", 100, 200,
native.systemFont, 16 )

Sprite Mtodo corona


Se obviara la sintaxis

*
-- primero creamos las opciones de hoja
local sheetOptions =
{
width = 512,
height = 256,
numFrames = 8
}
-- luego cargamos la imagen sprite
local sheet_runningCat =
graphics.newImageSheet( "sritepuma.png", sheetOptions )

--algunos mtodos (aplica para todos los objetos)


myText:setFillColor( 1, 0, 0 )

-- acto seguido creamos la secuencia


local sequences_runningCat = {
-- first sequence (consecutive frames)
{
name = "normalRun",
start = 1,
count = 8,
time = 800,
loopCount = 4
}
}
-- despus creamos el sprite
local runningCat = display.newSprite( sheet_runningCat,
sequences_runningCat )
--finalmente usamos sus mtodos
runningCat:translate(100,100) --opcional
runningCat:play()

Sprite mtodo texture packer


Se obviara la sintaxis

* loopDirection (forward y bounce ) en sequenceData


-- usa un archivo.lua generado por texture packer
-- primero llamamos al archivo .lua
local sheetInfo = require("spritesheet"), este contiene
las opciones de hoja y otros 2 metodos
--luego cargamos la imagen sprite
local miSprite =
graphics.newImageSheet("spritesheet.png",
sheetInfo:getSheet())
--despues creamos la secuencia
local sequenceData = {
{
name="walk",
-- name of the animation
sheet=miSprite,
-- the image sheet
start=sheetInfo:getFrameIndex("0001"), -- first frame
count=8,
-- number of frames
time=1000,
-- speed
loopCount=4
-- repeat
}
}
--finalmente creamos el sprite
sprite = display.newSprite( miSprite, sequenceData )
sprite:setSequence("walk")
---y le damos play
sprite:play()
---- tambin podemos obtener cualquier imagen de la hoja
--sprite asi
display.newImage(miSprite,
sheetInfo:getFrameIndex("0001"))

display.newRect( x, y, width, height )


display.newRect( parent, x, y, width,
height )

* propiedades x1,x2,x3,x4
--ejemplo
local myRectangle = display.newRect( 0, 0, 150, 50 )
--aplicando propiedades y metodos
myRectangle.strokeWidth = 3
myRectangle:setFillColor( 0.5 )
myRectangle:setStrokeColor( 1, 0, 0 )

display.newCircle( xCenter, yCenter,


radius )
display.newCircle( parent, xCenter,
yCenter, radius )

-- ejemplo con sus propiedades y metodos


local myCircle = display.newCircle( 100, 100, 30 )
myCircle:setFillColor( 0.5 )
myCircle.strokeWidth = 5
myCircle:setStrokeColor( 1, 0, 0 )

display.newRoundedRect( x, y, width,
height, cornerRadius )

-- ejemplo con sus propiedades y metodos


local myRoundedRect = display.newRoundedRect( 0, 0, 150,
50, 12 )
myRoundedRect.strokeWidth = 3
myRoundedRect:setFillColor( 0.5 )
myRoundedRect:setStrokeColor( 1, 0, 0 )

display.newRoundedRect( parent, x, y,
width, height, cornerRadius )

display.newLine( [parentGroup,] x1,


y1, x2, y2 [, x3, y3, ... ] )

local star = display.newLine( 200, 90, 227, 165 )


star:append( 305,165, 243,216, 265,290, 200,245, 135,290,

-- solo los dos primeros pares son


necesarios

157,215, 95,165, 173,165, 200,90 )


star:setStrokeColor( 1, 0, 0, 1 )
star.strokeWidth = 8

display.newPolygon( x, y, vertices )
display.newPolygon( parent, x, y,
vertices )

local halfW = display.contentWidth * 0.5


local halfH = display.contentHeight * 0.5
local vertices = { 0,-110, 27,-35, 105,-35, 43,16, 65,90,
0,45, -65,90, -43,15, -105,-35, -27,-35, }
local o = display.newPolygon( halfW, halfH, vertices )
o.fill = { type="image", filename="mountains.png" }
o.strokeWidth = 10
o:setStrokeColor( 1, 0, 0 )

display.newEmbossedText( [parentGroup,
] text, x, y, font, fontSize )
display.newEmbossedText( [parentGroup,
] text, x, y, [width, height,] font,
fontSize )

local myText = display.newEmbossedText( "hello", 200,


100, native.systemFont, 40 )
myText:setFillColor( 0.5 )
myText:setText( "Hello World!" )
local color =
{
highlight = { r=1, g=1, b=1 },
shadow = { r=0.3, g=0.3, b=0.3 }
}
myText:setEmbossColor( color )

display.newContainer( [parent, ]
width, height )

-- Create a container
local container = display.newContainer( 128, 128 )
-- Create an image
local bkgd =
display.newImage( "aquariumbackgroundIPhone.jpg" )
-- Insert the image into the container
container:insert( bkgd, true )
-- Center the container in the display area
container:translate( display.contentWidth*0.5,
display.contentHeight*0.5 )
-- Transition (rotate) the container
transition.to( container, { rotation=360,
transition=easing.inOutExpo} )

display.newSnapshot( w, h )

local snapshot = display.newSnapshot( 200, 200 )


math.randomseed( 0 ) random se palica solo 1 vez

display.newSnapshot( parent, w, h )
-- Add fish to the screen
for i=1,4 do
local fish = display.newImage( "fish.small.red.png" )
-- move to random position in a 200x200 region in the
middle of the screen
fish:translate( math.random( -100, 100 ),
math.random( -100, 100 ) )

-- insert fish into snapshot


snapshot.group:insert( fish )
end
snapshot:translate(160, 240) -- Center snapshot
snapshot:invalidate()
-- Invalidate snapshot
snapshot.alpha = 0.5
-- Apply to flattened image
EMISOR DE PARTICULAS (FUEGO)
Usar archivo .json, ah es donde se
hacen las modificaciones

-- Require the JSON library for decoding purposes


local json = require "json"
-- Read the exported Particle Designer file (JSON) into a
string
local filePath = system.pathForFile( "fire.json" )
local f = io.open( filePath, "r" )
local fileData = f:read( "*a" )
f:close()
-- Decode the string
local emitterParams = json.decode( fileData )
-- Create the emitter with the decoded parameters
local emitter1 = display.newEmitter( emitterParams )
-- Center the emitter within the content area
emitter1.x = display.contentCenterX
emitter1.y = display.contentCenterY

PROPIEDADES Y METODOS COMUNES


PROPIEDADES
-- propiedad alpha (poner transparecia)
local object = display.newImage( "image.png" )
object.alpha = 0.75 -- set to 75% opacity

METODOS
---- metodo contenToLocal
-- Rectangle that fills screen
local rect = display.newRect( 0, 0,
display.contentWidth, display.contentHeight )
rect.x = display.contentCenterX ; rect.y =
display.contentCenterY
rect.strokeWidth = 4 ; rect:setStrokeColor( 1,
0, 0 )
rect:setFillColor( 0, 0, 0 )
-- Create text objects to display content and
local coordinates
local contentText = display.newText( "", 0, 0,
display.nativeSystemFont, 16 )
local localText = display.newText( "", 0, 0,
display.nativeSystemFont, 16 )
localText.anchorX = 0 ; localText.anchorY = 0
contentText.anchorX = 0 ; contentText.anchorY =
0

function showCoordinates( event )


-- Get x and y of touch event in content
coordinates
local contentX, contentY = event.x, event.y
-- Convert to local coordinates of
local localX, localY =
event.target:contentToLocal( contentX, contentY
)
-- Display content and local coordinate
values
contentText.text = "CONTENT: " ..
tostring(contentX) .. ", " ..
tostring(contentY)
localText.text = "LOCAL: " ..
tostring(localX) .. ", " .. tostring(localY)
contentText.x, contentText.y = event.x+20,
event.y
localText.x, localText.y = event.x+20,
event.y+20
localText.anchorX = 0 ; localText.anchorY =
0
contentText.anchorX = 0 ;
contentText.anchorY = 0
return true
end
rect:addEventListener( "touch", showCoordinates
)

-- propiedad anchor (cambiar centro de


dibujo)
local rect2 = display.newRect( 0, 0, 50, 50 )
rect2.anchorX = 0 (0, 0.5 1)
rect2.anchorY = 0 (0, 0.5 1)

--Mtodo localToContent
-- Create a square
local square = display.newRect( 100, 100, 40,
40 )
square:setFillColor( 1 )
-- Create another square on top and rotate it
20 degrees
local redSquare = display.newRect( 100, 100,
40, 40 )
redSquare:setFillColor( 1, 0, 0, 0.6 )
redSquare.rotation = 20
local sqCenterX, sqCenterY =
square:localToContent( 0, 0 )
print( "White square's center position in
screen coordinates: ", sqCenterX, sqCenterY )
-- Get the content position of the white
square's top-left corner
-- Using ( -20,-20 ) specifies the top left

corner of the square, since it's 40x40 in size


local whiteTLX, whiteTLY =
square:localToContent( -20, -20 )
print( "White square's top-left position in
screen coordinates: ", whiteTLX, whiteTLY )
-- Get the content position of the red square's
top-left corner, independent of its rotation
-- Using ( -20,-20 ) specifies the top left
corner of the square, since it's 40x40 in size
local redTLX, redTLY =
redSquare:localToContent( -20, -20 )
print( "Red square's top-left position in
screen coordinates: ", redTLX, redTLY )

-- propiedad contentBound (obtener


lmites del objeto)

-- creando y borrando una imagen con


botones

local rect = display.newRect( 100, 100, 50,


50 )

local function dibujarCarro( event )


if event.phase == "ended" then
obj =

local bounds = rect.contentBounds


print( "xMin: ".. bounds.xMin ) -print( "yMin: ".. bounds.yMin ) -print( "xMax: ".. bounds.xMax ) -print( "yMax: ".. bounds.yMax ) --

display.newImageRect( "carro.png", 100,100 )


obj:translate( 100, 100 )
end
end

xMin:
yMin:
xMax:
yMax:

100
100
150
150

local function borraCarro( event )


--obj =
display.newImageRect( "carro.png", 100,100 )
--obj:translate( 250, 100 )
--display.newText("lo creo", 200, 350,
arial, 20)
if event.phase == "ended" then
obj:removeSelf()
obj = nil
contador=contador+20
display.newText("lo borro",
200, 400+contador, arial, 20)
end
end

local grupoBotonDibujar = display.newGroup()


local botonDibujar =
display.newRoundedRect( grupoBotonDibujar,0,0,
150, 50, 20 )
local textoDibujar =
display.newText( grupoBotonDibujar, "DIBUJAR",
0, 0, ARIAL, 20 )
textoDibujar:setFillColor(1, 0, 1, 1)
grupoBotonDibujar:translate(75,300)

local grupoBotonBorrar = display.newGroup()


local botonBorrar =
display.newRoundedRect( grupoBotonBorrar,0,0,
150, 50, 20 )
local textoBorrar =
display.newText( grupoBotonBorrar, "BORRAR", 0,
0, ARIAL, 20 )
textoBorrar:setFillColor(0,1,1,1)
grupoBotonBorrar:translate(245,300)
botonDibujar:addEventListener("touch",
dibujarCarro)
botonBorrar:addEventListener("touch",
borraCarro)

-- propiedad rotation (rotar un objeto)

-- rotando una recta

local rect = display.newRect( 100, 100, 50,


50 )
rect.rotation = 55 -- afecta el tamao

local rect = display.newRect( 50, 50, 100,


200 )
rect:setFillColor( 1, 0, 0 )

print( "contentHeight: ".. rect.contentHeight )


print( "contentWidth: ".. rect.contentWidth )

-- Rotate the rectangle 45 degrees


rect:rotate( 45 )

-- propiedad height, width (obtener


medida)

Escalando una imagen

local rect = display.newRect( 100, 100, 50,


50 )
rect:scale(2,2) no afecta al tamao

local star = display.newImage( "star.png" )


-- Scale the image by 200% (x) and 50% (y)
star:scale( 2, 0.5 )

print( "Height: ".. rect.height )


print( "Width: ".. rect.width )

-- propiedad maskScale (cambiar


tamao de una mascara)
-- Crea la imagen
local image =
display.newImageRect( "cuadrado.jpg", 200,
250 )
image:translate( display.contentCenterX,
display.contentCenterY )
-- crea la mascara y la aplica a la imagen
local mask = graphics.newMask( "gallina.jpg" )
image:setMask( mask ) -- metodo
-- Eventos de toque sobre la imagen se
enmascaran a los lmites de la mscara
--(Siempre rectangular para una imagen,
independientemente del contenido de la imagen)
image.isHitTestMasked = true
-- cambiando de tamao
image.maskScaleX, image.maskScaleY = 2,2

Poniendo mascara a una imagen


-- Create and position image to be masked
local image = display.newImageRect(
"image.png", 768, 1024 )
image:translate( display.contentCenterX,
display.contentCenterY )
-- Create mask and apply to image
local mask = graphics.newMask( "circlemask.png"
)
image:setMask( mask )
-- Transform mask
image.maskScaleX, image.maskScaleY = 2,2

-- propiedad parent ()

Poniendo mascara a un grupo

local group = display.newGroup() crea grupo

local g = display.newGroup()
-- Create and position image to be masked, and
insert into group
local image = display.newImageRect( g,
"image.png", 768, 1024 )

local rect = display.newRect( 100, 100, 50,


50 )
rect:setFillColor( 0.7 )
group:insert( rect ) instera (evitar)
rect.parent:remove( rect )
group

--removes rect from

-- Center the Display Group


g:translate( display.contentCenterX,
display.contentCenterY )
local mask = graphics.newMask("circlemask.png")
g:setMask(mask)

--rotacin sencilla

- crear cartas

local rect = display.newRect( 100, 100, 50,


50 )
rect.rotation = 45

local cards = display.newGroup()


-- grupo
de cartas
-- crear evento (toBack o toFront)
function sendToBack( event )
if ( event.phase == "began" ) then

-- transicin
local rect = display.newRect( 70, 150, 100, 150
)
rect:setFillColor( 1, 0, 0 )
--rect.rotation = -45
local reverse = 0 -- bit
-- funcion
local function rockRect()
if ( reverse == 0 ) then
reverse = 1
-- tiempo para la transicion
transition.to(rect, {time = 1000,
x=200})
else
reverse = 0
transition.to(rect, {time = 1000,
x=70})
end
end
--tiempo de inicio y duracion de cada ciclo de
la funcin
timer.performWithDelay( 2000, rockRect, 0 ) -Repite siempre

--rotacion con transicin


local rect = display.newRect( 50, 50, 100,
150 )
rect:setFillColor( 1, 0, 0 )
rect.rotation = -45
local reverse = 1
local function rockRect()

event.target:toFront()
end
return true
end
for i=1,5 do
--grupo de elementos de uan carta
local cardGroup = display.newGroup()
-- Card outline
local cardRect =
display.newRoundedRect(cardGroup, 100, 100,
125, 175, 12 )
cardRect.strokeWidth = 2
cardRect:setFillColor( 1 )
cardRect:setStrokeColor( 0, 0, 0, 0.3 )
cardGroup:insert(cardRect)
-- Card values
local cardValue =
display.newText( cardGroup, i,
cardRect.contentWidth - 72, 32,
native.systemFontBold, 24 )
cardValue:setFillColor( 1, 0, 0 )
local cardValue2 =
display.newText( cardGroup, i, 148,
cardRect.contentHeight - 8 ,
native.systemFontBold, 24 )
cardValue2:setFillColor( 1, 0, 0 )
cardGroup.x = (i * 25)
cardGroup.y = (i * 25)

if ( reverse == 0 ) then
reverse = 1
transition.to( rect, { rotation=-45,
time=500, transition=easing.inOutCubic } )
else
reverse = 0
transition.to( rect, { rotation=45,
time=500, transition=easing.inOutCubic } )
end
end
timer.performWithDelay( 600, rockRect, 0 ) -Repeat forever
-- propiedad x,y (esto ubica en el punto
donde le indicas)
-local rect = display.newRect( 0, 0, 50, 50 )
rect.x = 100
rect.y = 100

-- propiedad
objeto)

xScale (cambia tamao del

local rect1 = display.newRect( 100, 75, 150, 50


)
rect1:setFillColor( 1, 1, 1 )
rect1.rotation=30
-- gira el rectangulo horizontalmente
rect1.xScale = -1
local rect2 = display.newRect( 125, 175, 50, 50
)
rect2:setFillColor( 1, 0, 0 )
rect2.xScale = 2 -- cambia la escala en x a
200%
rect2.yScale = 1.5 -- cambia la escala en y a
150%

-- lee la ruta donde almacenas el .main


local line = display.newLine( 200, 90, 227, 165
)
print("line._defined: " .. line._defined )

-- lee la ruta del main.lua y la linea


donde fue
-- hecho el ultimo cambio
local line = display.newLine( 200, 90, 227, 165
)
line.rotation = 45
print("line._lastChange: " ..
line._lastChange )

cards:insert( cardGroup )
-- agregando evento a un grupo
cardGroup:addEventListener( "touch",
sendToBack )
end

--Esto aumenta en x o y
local cuadrado = display.newRect( 100, 100,
50, 50 )
cuadrado:setFillColor(1, 0, 0, 1)
cuadrado:translate(100
,100)

-- da las propiedades del objeto


local json = require( "json" )
local line = display.newLine( 200, 90, 227, 165
)
line.rotation = 45
print("line._properties: " ..
json.prettify( line._properties ) )

Mtodo de insercin directa

Mtodo directo

local myGroup = display.newGroup()

local myGroup = display.newGroup()

local myImage = display.newImage( myGroup,


"image.png" )

local myImage = display.newImage( "image.png" )


myGroup:insert( myImage )

Orden de los objetos


--creamos el grupo
local myGroup = display.newGroup()
--creamos los objetos
local square = display.newRect( myGroup, 0, 0, 100, 100 ) --red square is at the bottom
square:setFillColor( 1, 0, 0 )
local circle = display.newCircle( myGroup, 30, 50, 50 ) --green circle is in the middle
circle:setFillColor( 0, 1, 0 )
local rect = display.newRect( myGroup, 60, 50, 120, 80 ) --blue rectangle is at the top
rect:setFillColor( 0, 0, 1 )
myGroup:translate(100,100)
-- creamos el parend de square
local parent = square.parent
-- lo ponemos en su parent
parent:insert( square )
-- y ya podemos moverlo a la capa que queramos
parent:insert(1, circle )

Referencia a objetos (usando una tabla)


-- creamos un grupo
local squares = display.newGroup()
--creamos los cuadrados
local redSquare1 = display.newRect( squares, 0, 0, 40, 40 )
local redSquare2 = display.newRect( squares, 0, 50, 40, 40 )
local redSquare3 = display.newRect( squares, 0, 100, 40, 40 )
--los pinatmos de color rojo
redSquare1:setFillColor( 1, 0, 0 )

redSquare2:setFillColor( 1, 0, 0 )
redSquare3:setFillColor( 1, 0, 0 )
--creamos los cuadrados
local whiteSquare1 = display.newRect( squares, 0, 0, 40, 40 )
local whiteSquare2 = display.newRect( squares, 0, 70, 40, 40 )
--os pinatmos de color balnco
whiteSquare1:setFillColor( 1 )
whiteSquare2:setFillColor( 1 )
squares:translate(100,50)
--ponemos solo los cuadrados rojos en la tabla
local redSquares = { redSquare1, redSquare2, redSquare3 }
--manipulamos la tabla usando un for
for i = 1, #redSquares do
--manipulate the square at the current index (i)
redSquares[i].x = redSquares[i].x + 100 -- los movemos 100 a la derecha
redSquares[i]:scale( 0.5, 0.5 ) -- los escalos a 50 %
end

Borrado directo

Borrando un grupo

display.remove ( myObject )
myObject = nil --set reference to nil!

display.remove( myGroup )
myGroup = nil

--OR
myObject:removeSelf()
myObject = nil --set reference to nil!

--OR
myGroup:removeSelf()
myGroup = nil

--OR
myGroup:remove( myObject )
myObject = nil --set reference to nil!