Problems with score function in corona sdk (lua) - lua

Good evening,
I have a problem with the score function in my videogame.
I need it for a university exam.
in practice, in the video game the little man has to "save" the animals from the burning forest and jump over the sotacles.
when he goes on an animal the score increases, only that the score doubles and, after he has saved the first animal, the other elements invert the typical direction of travel. it almost seems that the little man pushes him in the opposite direction.
What could be the problem?
here the codes with the score function and the generation of the elements
local function updateScore()
scoreDisplay=display.newText(sceneGroup, "Score:", display.contentCenterX, display.contentCenterY-150, native.systemFont, 30)
scoreDisplay:setFillColor(black)
score = score + 1
scoreDisplay.text="Score:" .. score
end
-- Funzione per la creazione degli ostacoli e animali
local function createElement( event )
-- In base al numero cambia l'elemento caricato
local obstacle = math.random(4)
-- Ostacolo fiamma
if(obstacle == 1) then
element = display.newImageRect(sceneGroup,"img/flame.png", 80, 80);
element.myName = "obstacle"
-- L'elemento generato viene posizionato in modo casuale, ma entro i margini dello schermo
element.x = 1080
element.y = 100;
-- Aggiungiamo un corpo statico alla fiamma
physics.addBody(element, "dynamic", { bounce=0.0 })
-- Ostacolo roccia
elseif(obstacle == 2) then
element = display.newImageRect(sceneGroup,"img/rock.png", 70, 50);
element.myName = "obstacle"
element.x = 1080
element.y = 100;
-- Aggiungiamo un corpo statico alla roccia
physics.addBody(element, "dynamic", { bounce=0.0 })
-- Animale
elseif (obstacle == 3) then
element = display.newImageRect(sceneGroup,"img/rabbit.png", 80, 80);
element.myName = "animal"
element.x = 1080
element.y = 100;
-- Aggiungiamo un corpo statico al coniglio
physics.addBody(element, "dynamic", { bounce=0.0 })
elseif (obstacle==4) then
element = display.newImageRect(sceneGroup,"img/koala.png", 200, 120);
element.myName = "animal"
element.x = 1080
element.y = 100;
-- Aggiungiamo un corpo statico al koala
physics.addBody(element, "dynamic", { bounce=0.0 })
end
table.insert(elements, element)
return element
end
-- funzione che elimina gli ostacoli non attivi e ne crea di nuovi
-- e viene chiamato ogni secondo
and here the collision function
--funzione che implementa le collisioni
local function onCollision(self,event)
if (event.phase=="began") then
-- self rappresenta l'oggetto badGuy
-- event.other rappresenta l'altro ogetto
-- coinvolto nell'urto
if event.other.myName=="ground" and event.contact.isTouching==true then
self.action="run"
end
if ((event.other.myName=="animal" and self.myName=="boy") or (event.other.myName=="animal" and self.myName=="boy")) then
if(event.contact.isTouching==true) then
updateScore()
end
event.contact.isTouching=false
transition.fadeOut( event.other, { time = 30 } )
print("score")
end
end
--se la collisione avviene tra boy, la fiamma e la roccia
if ((event.other.myName=="obstacle" and self.myName=="boy") or (event.other.myName=="boy" and self.myName=="obstacle")) then
physics.pause()
display.remove(boy)
boy = nil
--rimozione suono in sottofondo
audio.stop(playSound)
playSound=nil
--liberazione memoria
audio.dispose(playSound)
--rimozione listener dello sfondo
Runtime:removeEventListener("enterFrame", bosco1)
Runtime:removeEventListener("enterFrame", bosco2)
--rimozione listener terreno
Runtime:removeEventListener("enterFrame", terreno1)
Runtime:removeEventListener("enterFrame", terreno2)
--rimozione listener collisioni
Runtime:removeEventListener("enterFrame", onCollision)
--Rimozione listener per il tap di boy
Runtime:removeEventListener("tap", boyJump)
--stoppamente generazione nuovi elementi
timer.cancel(gameLoopTimer)
composer.gotoScene("restart",{ time=800, effect="crossFade" } )
end
end
who can help me? thanks!

Related

plese help me to solve Error main.lua:50: attempt to index global 'coin' (a nil value)

how do i use the Table coin in the function love.graphic.rettangle without making it global? I declare the table in a love.update() function (I don't know if anything changes)
if math.random() < 0.01 then --math.rand restituisce numeri da 0 a 1 (la usiamo come probabilità)
local coin = {}
coin.h = 80
coin.w = 80
coin.x = math.random(0, 800 - coin.w)
coin.y = math.random(0, 800 - coin.h)
table.insert(coins, coin)-- inseriamo nella table coins il table coin appena creato
end
end
function love.draw()
--[[love.graphics.setBackgroundColor( 255, 150, 150)
love.graphics.setColor(255, 0, 0)]]
love.graphics.setColor(255, 0, 0)
love.graphics.rectangle("fill", player.x, player.y, player.w, player.h)
love.graphics.setColor(255, 255, 0)
for i=1, #coins, 1 do
love.graphics.rectangle("fill", coin.x, coin.y, coin.w, coin.w, coin.h)
end
end
for i=1, #coins, 1 do
love.graphics.rectangle("fill", coin.x, coin.y, coin.w, coin.w, coin.h)
end
In the scope of your function love.draw, coin is a nil value.
coin is local to the followin if statement and hence cannot be used outside.
if math.random() < 0.01 then --math.rand restituisce numeri da 0 a 1 (la usiamo come probabilità)
local coin = {}
coin.h = 80
coin.w = 80
coin.x = math.random(0, 800 - coin.w)
coin.y = math.random(0, 800 - coin.h)
table.insert(coins, coin)-- inseriamo nella table coins il table coin appena creato
end
But as you inserted the local coin into coins you can access each coin by indexing coins if draw.love is in its scope.
So instead of the for loop above write
for i=1, #coins, 1 do -- the third parameter defaults to 1 so for i = #coins do is enough
local coin = coins[i]
love.graphics.rectangle("fill", coin.x, coin.y, coin.w, coin.w, coin.h)
end
As coins is a sequence you could also use a generic for loop with ipairs
You probably have a coin.w to many btw.
for _, coin in ipairs(coins) do
love.graphics.rectangle("fill", coin.x, coin.y, coin.w, coin.h)
end

rotate over widgets in a stack layout

I'm trying to create a widget to control screens brightness.
I have a widget.interfaces table containing interfaces names (from xrandr)
ans below is the widget with which I have problems:
when I use mouse right-click, there's no changeof sub-widget. I suspect the right-click event is propogated to each sub-widget and I turn back to the same text display
when I use mouse-grab to change slider value, awesome complains about
mousegrabber already running. I suspect the event is, once again propagate...
Don't know how to handle these problems.
function widget.sliderBrightnessWidget()
--
local MAX = 100
local maxi = 2
local MIN = 0
local mini = .5
--
local leswidgets = wibox.widget({
forced_width = 150,
layout = wibox.layout.stack
})
--
for i, iface in ipairs(widget.interfaces) do
-- la barre
local slider = wibox.widget {
bar_shape = gears.shape.rounded_rect,
bar_height = 1,
bar_color = beautiful.border_color,
handle_shape = gears.shape.circle,
handle_color = fu.couleurBarre(beautiful.widget_sliderBrightness_handle_color_type, 100, MIN, MAX),
minimum = MIN,
maximum = MAX,
widget = wibox.widget.slider,
}
-- le texte
local sliderTexte = wibox.widget(
{
markup = "<span foreground='white'>" .. iface .. "</span>",
align = "center",
widget = wibox.widget.textbox
}
)
-- le widget complet
local unWidgetComplet = wibox.widget(
{
{
sliderTexte,
slider,
vertical_offset = 0,
layout = wibox.layout.stack
},
bg = beautiful.noir,
widget = wibox.container.background
}
)
-- callback changement de la barre
unWidgetComplet:connect_signal("property::value", function()
local v = tostring(mini + (slider.value * (maxi - mini) / MAX))
v = v:gsub(",",".")
local command="xrandr --output " .. iface .." --brightness " .. v
fu.commandeExecute(command)
slider.handle_color = fu.couleurBarre(beautiful.widget_sliderBrightness_handle_color_type, v, mini, maxi)
end)
-- callbak changement de widget
unWidgetComplet:buttons(
gears.table.join(
awful.button({}, 3,
function()
widget.activeIndex = 1 + widget.activeIndex%#widget.interfaces
leswidgets:raise(widget.activeIndex)
end
)
)
)
leswidgets:add(unWidgetComplet)
end
--
return leswidgets
end

Lua / corona sdk physics.addBody()

When my ball hits but 30 targets 30 new returns except I have an error message lua:76: physics.addBody() cannot be called when the world is locked and in the middle of number crunching, such as during a collision event why ?
function CreeNiveau()
print("Crée le Niveau 1 ")
local lig,col ,x,y
local largeurColonne = (display.actualContentWidth/(5+1))
x = display.screenOriginX + largeurColonne
y = display.screenOriginY + 100
-- si une cible et toucher la Remove et donne des point
local function onToucheCible(self, event)
if event.phase == "began" then
audio.play(sonBump)
self:removeSelf()
AjouteScore(25)
nbCible = nbCible - 1
print("Nombre de cible restent", nbCible)
if nbCible == 0 then
Recible()
end
end
end
for lig = 1,6 do
for col = 1, 5 do
local cible = display.newCircle(x,y, 8)
-- couleur des cible
cible:setFillColor(1,math.random(),math.random())
physics.addBody( cible, "static", { density = 1, friction = 0.3, bounce = 0.6, radius = 8})
cible.collision = onToucheCible
cible:addEventListener("collision")
globaleview:insert(cible)
x = x + largeurColonne
end
y = y + 50
x = display.screenOriginX + largeurColonne
end
You probably use physics functions/APIs in collision listener. Use timer.performWithDelay to delay execution of Recible function:
local function onToucheCible( self, event )
if event.phase == "began" then
audio.play( sonBump )
self:removeSelf()
AjouteScore( 25 )
nbCible = nbCible - 1
print("Nombre de cible restent", nbCible)
if nbCible == 0 then
timer.performWithDelay( 50, Recible )
end
end
end
Read more:
physics.addBody() cannot be called
physics.addBody cannot be called when the world is locked and in the middle of number crunching such as during a collision event

Lua - Error Attempt to perform arithmetic on field '?' -- This occurs at the end of the for loop

I'm developing a program for the Ti-nspire CX CAS calculator and at the time of execution it indicates an error on line 52, this is presented at the end of the for loop in the "area" function.
Sorry for my English.
local coX = {0,2,2,0}
local coY = {0,0,2,0}
local xmax = 2
local ymax = 2
-- Matriz de coordenadas para función "on.paint(gc)"
function conCoor(x,y)
local nx = x
for i=1, #x do
table.insert(nx,i*2,y[i])
end
return nx
end
-- Valor absoluto
function math.abs(valor)
if valor < 0 then
valor = valor*(-1)
end
return valor
end
-- Inercia del polígono respecto el eje X
function inerciex(x,y)
local E = 0
local z =0
for i = 1, #x-1 do
E = (x[i+1]-x[i])*(y[i+1]+y[i])*((y[i+1])^2+(y[i])^2)
z = E + z
end
return math.abs(z/12)
end
-- Inercia del polígono respecto el eje Y
function inerciey(x,y)
local E = 0
local z =0
for i = 1, #x-1 do
E = (y[i+1]-y[i])*(x[i+1]+x[i])*((x[i+1])^2+(x[i])^2)
z = E + z
end
return math.abs(z/12)
end
-- Área del poligono
function area(x,y)
local A = 0
local z = 0
for i = 1, #x-1 do
A = (y[i]*x[i+1]-x[i]*y[i+1])
z = A + z
end -- Line 52, the line in question
return math.abs(z/2)
end
-- Centro de masa del polígono (eje x)
function centroix(x,y)
local Ac = area(x,y)
local z = 0
local cx = 0
for i = 1, #x-1 do
cx = (x[i]+x[i+1])*(x[i]*y[i+1]-x[i+1]*y[i])
z = cx + z
end
return z/(6*Ac)
end
-- Centro de masa del polígono (eje y)
function centroiy(x,y)
local Ac = area(x,y)
local z = 0
local cx = 0
for i = 1, #x-1 do
cx = (y[i]+y[i+1])*(x[i]*y[i+1]-x[i+1]*y[i])
z = cx + z
end
return z/(6*Ac)
end
-- Escala de figura
function escala(xmax,ymax)
local sc = 0
if xmax > ymax then
sc = 81/xmax
else
sc = 81/ymax
end
return math.floor(sc)
end
-- Coordenadas del origen en pantalla
function oriDispX(x,y,xmax,ymax)
return math.floor(212 + (-1)*centroix(x,y)*escala(xmax,ymax))
end
function oriDispY(x,y,xmax,ymax)
return math.floor(105 + (-1)*centroiy(x,y)*escala(xmax,ymax))
end
-- Cambio de coordenadas real
function coorCamb(x,y,xmax,ymax)
-- Escalado de coordenadas
local escx = x
local escy = y
local orix = oriDispX(escx,escy,xmax,ymax)
local oriy = oriDispY(escx,escy,xmax,ymax)
for i = 1, #escx do
escx[i] = math.floor(escx[i]*escala(xmax,ymax))
escy[i] = math.floor(escy[i]*escala(xmax,ymax))
end
-- Cambio de coordenadas
for i = 1, #escx do
escx[i] = escx[i] + orix
escy[i] = escy[i] + oriy
end
return conCoor(escx,escy)
end
function on.paint(gc)
local ox = oriDispX(coX,coY,xmax,ymax)
local oy = oriDispY(coX,coY,xmax,ymax)
local c = coorCamb(coX,coY,xmax,ymax)
gc:drawPolyLine(c)
gc:drawLine(ox-3,oy,ox+3,oy)
gc:drawLine(ox,oy-3,ox,oy+3)
gc:fillArc(ox-1,oy-1,2,2,0,360)
gc:fillArc(212-1,105-1,2,2,0,360)
gc:drawString(tostring(area(coX,coY)),10,10)
platform.window:invalidate()
end
More specifically, the error occurs here:
function area(x,y)
local A = 0
local z = 0
for i = 1, #x-1 do
A = (y[i]*x[i+1]-x[i]*y[i+1])
z = A + z
end -- Line 52, the line in question
return math.abs(z/2)
end
Your code assumes both X and Y arrays are of equal size (because you use i index for both X and Y array), or at least Y never smaller than X. i index, however, runs from 1 to the size of X array which will be invalid for Y array of smaller size.
So, if the Y array is smaller than the X array, you get that error. And, here's the proof:
function area(x,y)
local A = 0
local z = 0
for i = 1, #x-1 do
A = (y[i]*x[i+1]-x[i]*y[i+1])
z = A + z
end
return math.abs(z/2)
end
print(area({1,2,3},{4,5,6})) -- OK
print(area({1,2,3},{4,5})) -- ERROR
The solution was to initialize the variables and tables at the beginning of the whole script and then call the new values ​​using "var.recall" inside the on.paint function.

Corona SDK Attempt to compare number number to nil

Hi I am converting this simple "catch the egg" game from Godot engine to Corona. I am very new to programming and am using this project as a learning exercise.
I have run into a hurdle with it though. I keep getting the following error msg:
**
ERROR: Runtime error
C:\Users\kdoug\Documents\Corona Projects\cathchtheegg\main.lua:19: attempt to compare number with nil
stack traceback:
C:\Users\kdoug\Documents\Corona Projects\cathchtheegg\main.lua:19: in function
?: in function
**
What I am trying to do is see if the egg will delete when it goes beyond a certain point, without having to use a collision with a physics object.
any help would be appreciated!
thanks
Here is the code (a little less discombobulated):
local physics = require "physics"
physics.start()
local h = display.actualContentHeight
local w = display.actualContentWidth
local cx = display.contentCenterX
local cy = display.contentCenterY
local dnir = display.newImageRect
local dnr = display.newRect
local mr = math.random
--local egg
local bask
local idx = 0
local eggs = {}
---------BACKGROUND---------------
local bg = dnir("bg.png", w,h)
bg.x = cx
bg.y = cy
----------DISPLAY BASKET------------
bask = dnir("basket.png", 100,50)
bask.x = cx
bask.y = cy
physics.addBody(bask,"kinematic")
bask.myName = "bask"
----- BASKET MOVE W/ MUSE FUNCTION -----
local function baskMove (e)
bask.x = e.x
bask.y = e.y
end
Runtime:addEventListener("mouse", baskMove)
----------------GROUND---------------
local grd = dnr(cx,h-470,w+50,10)
grd:setFillColor(.1, .8, .15,0)
grd.myName = "ground"
physics.addBody(grd, "static")
grd.collision = collision
grd:addEventListener("collision", grd)
----------****DELETE EGG FUNCTION****------------
--function loop ()
-- if egg and egg.y > 100 then
-- print("Delete")
-- display.remove(egg)
-- end
--end
--
--Runtime:addEventListener("enterFrame", loop)
-----------COLLISIONS FUNCTIION-------------
local function collision ( s, e )
if e.phase == "began" then
if e.target.myName == "bask"
and e.other.myName == "egg" then
display.remove(e.other)
table.remove(eggs, idx)
end
if e.target.myName == "egg"
and e.other.myName == "bask" then
display.remove(e.target)
table.remove(eggs, idx)
end
if e.target.myName == "ground"
and e.other.myName == "egg" then
display.remove(e.other)
table.remove(eggs, idx)
end
if e.target.myName == "egg"
and e.other.myName == "ground" then
display.remove(e.target)
table.remove(eggs, idx)
end
end
end
--
--------------EGG---------------------
function theEgg ()
egg = dnir("egg.png", 50,50)
physics.addBody(egg,"dynamic")
egg.myName = "egg"
idx = idx + 1
egg.x = mr(w)
egg.y = - 100
transition.to (egg, {y = h + 50, time= mr(1000,8000)})
eggs[idx] = egg
eggs[idx].idx = idx
print(eggs[idx])
--------EGG COLLISIION CB-------------
egg.collision = collision
egg:addEventListener("collision", egg)
end
--
-----------Spawn EGG-----------
function spawner()
theEgg()
print(#eggs)-- PRINT AMT IN TABLE
end
timer.performWithDelay(2000, spawner, 0)
I don't know when you remove enterFrame listener. It is important. After you delete egg object loop may be called again. So when egg.y is not defined (=nil) comparision (in if statment) can not be done.
My solution:
function loop ()
if egg and egg.y > 100 then
print("Delete")
display.remove(egg)
end
end
Information from https://www.lua.org/pil/3.3.html
all logical operators consider false and nil as false and anything
else as true
Or (use local variable index instead global variable egg) It is not clear for my purpose use of varaible egg in your code so it may be wrong.
local index
...
function loop ()
if eggs[index] and eggs[index].y > 100 then
print("Delete")
local egg = table.remove(eggs, index)
display.remove(egg)
egg = nil
end
end

Resources