Corona SDK: Inserting into tables - coronasdk

I've read the other topics related to this subject and cannot make sense of them in the sense of my code. In the code below, I cannot get the make other word buttons into the table. I can generate the words but they will not go into the table. The previous function with the correct word works fine. What am I doing wrong? Do I have problems elsewhere in the code?
--main text
local content = require "content"
--chooses a random number according to the maximum number available in the table
local defaultWidth = 1024
local defaultHeight = 768
local displayWidth = display.viewableContentWidth
local displayHeight = display.viewableContentHeight
local yMargin = 20
local centerX = defaultWidth/2;
local centerY = defaultHeight/2;
local xAdjust = (defaultWidth - display.viewableContentWidth)/2
local yAdjust = (defaultHeight - display.viewableContentHeight)/2
local rnd = math.random
local maxSightwords = 3
local currQuestion = 0
local playOrder
local letterButtons
local wrongGraphic
local correctButton
--local wordButtons
function getRandomOrder(amount)
local order ={}
local i
local temp
local temp1
for n = 1,amount do
order[n] = n
end
for i=0,9 do
for temp = 1,amount do
n = math.random(1, amount)
temp1 = order[temp]
order[temp] = order[n]
order[n] = temp1
end
end
return order
end
-- assign random order for words
playOrder = getRandomOrder(#content)
function nextQuestion()
-- update question number index
currQuestion = currQuestion+1
if currQuestion > #playOrder then
currQuestion = 1
end
local questionNumber = playOrder[currQuestion]
print("Question# "..currQuestion)
print("id "..content[questionNumber].id)
-- make word buttons
wordButtons = {}
-- make word button for correct word
local word = content[playOrder[currQuestion]].word
table.insert(wordButtons, newWordButton(word))
correctButton = wordButtons[1].graphics
local buttonWidth = 150
print ("correct: "..word)
print (#wordButtons)
---[[
-- ****make other word buttons***
local otherWords = getRandomWords(content.word)
--print (otherWords)
for i=1, maxSightwords-1 do
table.insert(wordButtons, otherWords)
end
--]]
print (#wordButtons)
-- position letter buttons and add touch event listener
local randomWordOrder = getRandomOrder(#wordButtons)
local buttonSpacing = buttonWidth * 1.5
local buttonsWidth = (#wordButtons * buttonWidth) + ((#wordButtons-1) * (buttonSpacing/4))
local buttonsX = centerX - (buttonWidth)
for i=1, #wordButtons do
local button = wordButtons[i].graphics
button.y = centerY
button.x = buttonsX + (buttonSpacing * (randomWordOrder[i]-1))
button:addEventListener("touch", onWordTouch)
--local randomDelay = transitionDuration + (math.random(1,10) * 10)
--transition.from(button, {time = 500, delay = randomDelay, y = defaultHeight + button.height})
end
end
function clearQuestion()
-- remove wrongGraphic if present
if wrongGraphic then
wrongGraphic:removeSelf()
wrongGraphic = nil
end
-- remove all word buttons
for i=1,#wordButtons do
wordButtons[i].graphics:removeSelf()
wordButtons[i].graphics = nil
end
end
function onWordTouch(event)
local t = event.target
if "ended" == event.phase then
if t == correctButton then
onCorrect()
else
onIncorrect(t)
end
end
end
function onIncorrect(incorrectButton)
media.playSound("sounds/splat.wav")
wrongGraphic = display.newImageRect("images/graphics/wrong.png", 137, 136)
wrongGraphic.x = incorrectButton.x + incorrectButton.width/2
wrongGraphic.y = incorrectButton.y + incorrectButton.height/2
transition.to(incorrectButton, {time=100, delay=500, alpha=0})
transition.to(wrongGraphic, {time=200, delay=500, alpha=0, onComplete=wrongCompleteListener})
local wrongCompleteListener = function(obj)
obj:removeSelf()
obj = nil
incorrectButton:removeSelf()
incorrectButton = nil
end
end
function onCorrect()
-- play correct sound then display word
media.playSound("sounds/correct.mp3", playWord)
-- remove the letter buttons
clearQuestion()
-- disable the home button until new screen is shown
homeEnabled = false
end
function newWordButton(word)
local wordGraphic = display.newImageRect("images/words/"..word..".png", 150, 75)
local wordButton = {}
wordButton.graphics = display.newGroup()
wordButton.graphics:insert(wordGraphic)
wordButton.word = word
return wordButton
end
function getRandomWords ()
local wordGraphic = display.newGroup ()
for i=1,maxSightwords-1 do
--remove a word from content using a random index #
--Since the index will be between 1 and the number of words in content
--and each time through the loop a word is removed, you can be sure
--You will get 3 different words without repeats.
local next_word = table.remove(content, math.random(#content))
--next_word is a table with 'word' and 'id' fields so you can make the text display object from next_word.word
local wordText = display.newImageRect("images/words/"..next_word.id..".png", 150, 75)
wordText.x = display.contentWidth/2
wordText.y = display.contentHeight/2 - 100
wordGraphic:insert(wordText)
print (next_word.id)
end
end
nextQuestion ()

I think your problem is that you are resetting the wordButton = {} again in function newWordButton. You already made the table in function nextQuestion(), so by calling it again in the newWordButton function is reseting the entire table.
Take a look at this links:
http://www.coronalabs.com/blog/2011/06/21/understanding-lua-tables-in-corona-sdk/
http://docs.coronalabs.com/api/library/table/insert.html
I'm pretty sure the function should look like this:
function newWordButton(word)
local wordGraphic = display.newImageRect("images/words/"..word..".png", 150, 75)
wordButton.graphics = display.newGroup()
wordButton.graphics:insert(wordGraphic)
wordButton.word = word
return wordButton
end

Related

Xonix Game Optimization Problems

I'm doing a Xonix game on corona sdk. As a playing field, I decided to use a grid of squares. Width 44, Height 71. As a result, I received a row consisting of 3124(44*71) squares along which the player moves. But I have problems with optimization. The engine can not cope with such a number of squares on the screen at the same time. Because of this, FPS on a smartphone is not more than 12. Help me find the best solution. All that concerns polygons and meshes, I am not strong in geometry ((((
Reducing the number of squares is a bad idea. Then the appearance is lost, and the field is captured too large pieces.
Thank you in advance!
-- Creating a playing field
M.create_pole = function()
-- init
local image = display.newImage
local rect = display.newRect
local rrect = display.newRoundedRect
local floor = math.floor
M.GR_ZONE = display.newGroup()
M.POLE = {}
-- bg
M.POLE.bg = rrect(0,0,150,150,5)
M.POLE.bg.width = M.width_pole
M.POLE.bg.height = M.height_pole
M.POLE.bg.x = _W/2
M.POLE.bg.y = _H/2
M.POLE.bg.xScale = _H*.00395
M.POLE.bg.yScale = _H*.00395
M.POLE.bg:setFillColor(API.hexToCmyk(M.color.land))
M.GR:insert(M.POLE.bg)
M.POLE.img = image(IMAGES..'picture/test.jpg')
M.POLE.img.width = M.width_pole-M.size_xonix
M.POLE.img.height = M.height_pole-M.size_xonix
M.POLE.img.x = _W/2
M.POLE.img.y = _H/2
M.POLE.img.xScale = _H*.00395
M.POLE.img.yScale = _H*.00395
M.POLE.img.strokeWidth = 1.3
M.POLE.img:setStrokeColor(API.hexToCmyk(M.color.img))
M.GR:insert(M.POLE.img)
-- control player
M.POLE.bg:addEventListener( 'touch', M.swipe )
M.POLE.bg:addEventListener( 'tap', function(e)
M.POLE.player.state = 0
end )
-- arr field
M.arr_pole = {} -- newRect
local jj = 0
for i=1,M.delta_height do -- 71 point
M.arr_pole[i] = {}
M.GUI.border[i] = {}
for k=1,M.delta_width do -- 44 point
jj = jj+1
M.arr_pole[i][k] = {nm = jj}
M.GUI.border[i][k] = {}
local xx = k*M.size_xonix
local yy = i*M.size_xonix
local _x = floor(xx-M.size_xonix/2)
local _y = floor(yy-M.size_xonix/2)
M.arr_pole[i][k][1] = image(IMAGES..'pole/land.jpg')
M.arr_pole[i][k][1] .x = _x
M.arr_pole[i][k][1] .y = _y
M.GR_ZONE:insert(M.arr_pole[i][k][1])
-- water at the edges
-- the rest is land
if (i==1 or i==M.delta_height)
or (k==1 or k==M.delta_width) then
M.arr_pole[i][k].type = 0
else
M.arr_pole[i][k].type = 2
M.arr_pole[i][k][1].isVisible = true
end
end
end
M.GR_ZONE.width = M.POLE.bg.width*M.POLE.bg.xScale
M.GR_ZONE.height = M.POLE.bg.height*M.POLE.bg.yScale
M.GR_ZONE.x = M.POLE.bg.x-M.POLE.bg.width*M.POLE.bg.xScale/2
M.GR_ZONE.y = M.POLE.bg.y-M.POLE.bg.height*M.POLE.bg.yScale/2
-- player
local _x = M.arr_pole[1][1][1].x
local _y = M.arr_pole[1][1][1].y
M.POLE.player = image(IMAGES..'ui/player.png')
M.POLE.player.x = _x
M.POLE.player.y = _y
M.POLE.player.width = M.size_xonix*1.5
M.POLE.player.height = M.size_xonix*1.5
M.POLE.player.state = 0
M.GR_ZONE:insert(M.POLE.player)
M.POLE.player:toFront()
end
-- get all free cells
- land
M.get_free = function(_i,_j,_start)
local _par = pairs
local _fill = M.filling_arr
local _arr = M.arr_pole
local _index = {
{-1,-1}, {0,-1}, {1,-1},
{-1, 0}, {1, 0},
{-1, 1}, {0, 1}, {1, 1},
}
-- mark as verified
_arr[_i][_j].is_check = true
_fill[#_fill+1] = {_i,_j}
for k,v in _par(_index) do
local i = _i+v[1]
local j = _j+v[2]
if i>1 and i<M.delta_height
and j>1 and j<M.delta_width then
if not _arr[i][j].is_check then
if _arr[i][j].type==2 then
M.get_free(i,j)
end
end
end
end
if _start then
return _fill
end
end
-- fill(capture)
M.filling = function()
-- init
local par = pairs
local tb_rem = table.remove
local arr = M.arr_pole
M.island_arr = {}
-- check indicator
for i,ii in par(arr) do
for j,jj in par(ii) do
if jj.type==2 then
jj.is_check = false
end
end
end
-- we divide land into islands
for i,ii in par(arr) do
for j,jj in par(ii) do
if jj.type==2 and not jj.is_check then
M.filling_arr = {}
M.island_arr[#M.island_arr+1] = M.get_free(i,j,true)
end
end
end
- find a larger island and delete it
local sel_max = {dir = '', count = 1}
for k,v in par(M.island_arr) do
if #v>=sel_max.count then
sel_max.dir = k
sel_max.count = #v
end
end
if #M.island_arr>0 then
tb_rem(M.island_arr,sel_max.dir)
end
-- fill
for k,v in par(M.island_arr) do
for kk,vv in par(v) do
local obj = arr[vv[1]][vv[2]]
obj.type = 0
obj[1].isVisible = false
end
end
-- turning the edges into water
for k,v in par(M.bread_crumbs) do
local arr = arr[v.arr_y][v.arr_x]
arr.type = 0
arr[1].isVisible = false
end
M.clear_history()
end

Receiving "Attempt to index global 'sprite' (a nil value)" in Lua

Im attempting to make a simple game app and keep running into this problem. I stopped programming in Lua for a few years so I don't exactly remember how to fix this. Anyway, my code is as follows:
EDIT: Here is the entire file. Still trying to figure out the formatting of Stack Overflow. Error occurs at line 76.
module(..., package.seeall)
-- Main function - MUST return a display.newGroup()
function new()
local localGroup = display.newGroup()
---------
local Rad = math.rad
local Sin = math.sin
local Cos = math.cos
local Pi = math.pi
local Atan2 = math.atan2
local radD = 180 / Pi
local DegR = Pi / 180
local touchPoint = display.newCircle(localGroup, -50, -50, 20)
touchPoint.isFocus = false
touchPoint.alpha = 0
function GetDistanceFromObjects(obj1, obj2)
local xDist = obj1.x - obj2.x
local yDist = obj1.y - obj2.y
local dist = Sqrt((xDist * xDist) + (yDist * yDist))
return dist
end
function getAngleDeg(inX1, inY1, inX2, inY2)
local xDist = inX2 - inX1
local yDist = inY2 - inY1
local angRad = Atan2(yDist, xDist)
return angRad * radD + 90
end
require "sprite"
function VectorFromAngle(inAngle, inVelocity)
local vx = Cos(Rad(inAngle-90))
local vy = Sin(Rad(inAngle-90))
if(inVelocity ~= nil)then
vx = vx * inVelocity
vy = vy * inVelocity
end
return vx,vy
end
require ( "physics" )
physics.start()
physics.setGravity( 1, 1 )
--( x, y )
--physics.setDrawMode ( "hybrid" )
math.randomseed(os.time())
local background = display.newImage("yazd.jpeg")
localGroup:insert(background)
--width of image divided by # of pics lined up from left to right (in the sprite) = the first #
--height of image divided by # of pics lined up from top to bottom (in the sprite) = the second #
local birdSheet = sprite.newSpriteSheet( "enemy.jpg", 59, 50 )
local birdSet = sprite.newSpriteSet(birdSheet, 1, 1)
-- images 1-14
sprite.add( birdSet, "bird", 1, 1, 200, 0 )
-- play 1-14, each image every 200 ms, 0 = loop count, which is infinite
local bird1 = sprite.newSprite( birdSet )
bird1.x = 40 -- starting point
bird1.y = 40 -- starting point
bird1.xScale = 0.5 --scale down x
bird1.yScale = 0.5 --scale down y
bird1:prepare("bird") --prepare sprite sequence
bird1:play() --play sprite
localGroup:insert(bird1)
--only local to this group
local killSheet = sprite.newSpriteSheet("explosion.png", 100, 100)
local killSet = sprite.newSpriteSet(killSheet, 1, 9)
sprite.add(killSet, "kill", 1, 9, 200, 1)
local birdCount = 1
local transDirection12
local function transDirection1()
bird1.xScale = 0.5
transition.to(bird1, {time=math.random(200,500), x = math.random(200,490), y = math.random(10,310), alpha = (math.random(9,100))/100, onComplete = transDirection12})
end
transDirection12 = function()
bird1.xScale = 0.5
transition.to(bird1, {time= math.random(200,500), x = math.random(200,490), y = math.random(10,310), alpha = (math.random(9,100))/100, onComplete = transDirection1})
end
transDirection1()
-- local transDirection1 declares what will be used (local function)
-- transDirection1 = function
-- following it are the function qualities
-- declares it will use object/image called bird1 and scales it to .5
-- time = ____ means it will take a certain time, between ____ and ____ to complete the transition
-- x=____ means that is where it will move to on the x axis
-- y=____ means that is where it will move to on the y axis
-- alpha = ___ means the is how transparent it will be
-- onComplete = ________ means that when the action is complete, it will call another function
-- The next function has the same qualities as transDirection1, but the onComplete part calls transDirection1 and they continue to loop
-- transDirection1() declares transDirection1 so the app knows about it and can use it
-- the other trans do not need to be declared because they are part of transDirection1, which is already declared
--(x, y, size.x, size.y)
local player = display.newImage( "mk11.png" )
player.x = 240
player.y = 260
player.xScale = .5
player.yScale = .5
localGroup:insert( player )
-- add physics to all the objects wanted: (object wanted, "static" or "dynamic")
physics.addBody(player, "static", {radius=30, isSensor = true})
physics.addBody(bird1, "static", {radius=23})
local function shoot(inPointX, inPointY)
-- (start at the x of the player + 10, also start at the y of the player, the radius of the circle is 5)
local bullet = display.newImage( "bullet2.png" )
bullet.x = player.x
bullet.y = player.y
-- add physics to the object, which is the bullet.
-- Make the bullet "dynamic" or moving
physics.addBody(bullet, "dynamic")
bullet.isFixedRotation = true
localGroup:insert( bullet )
local velocity = 300
local vx, vy = VectorFromAngle(player.rotation, velocity)
bullet.rotation = player.rotation
bullet:setLinearVelocity(vx, vy)
end
function RotateToTouchPoint(inPointX, inPointY)
local ang = getAngleDeg(player.x, player.y, inPointX, inPointY)
player.rotation = ang
end
local function ScreenTouchListener(event)
local phase = event.phase
if(phase == "began")then
if(touchPoint.isFocus == false)then
touchPoint.alpha = 1
touchPoint.x = event.x
touchPoint.y = event.y
display.getCurrentStage():setFocus(touchPoint, event.id)
touchPoint.isFocus = true
RotateToTouchPoint(event.x, event.y)
shoot(event.x, event.y)
end
elseif(touchPoint.isFocus)then
if(phase == "moved")then
touchPoint.x = event.x
touchPoint.y = event.y
RotateToTouchPoint(event.x, event.y)
elseif(phase == "ended" or phase == "cancelled")then
display.getCurrentStage():setFocus(touchPoint, nil)
touchPoint.isFocus = false
touchPoint.alpha = 0
end
end
return true
end
local function gotShot (event)
event.target:removeSelf()
event.other:removeSelf()
local explosion = sprite.newSprite(killSet)
explosion.x, explosion.y = event.target.x, event.target.y
explosion:prepare("kill")
explosion:play()
localGroup:insert( explosion )
birdCount = birdCount - 1
-- when there are no more birds, remove the runtime event listener and perform the
-- function with a delay of 500 m.s. The function changes the scene to test.lua
if "ended" then
if birdCount == 0 then
Runtime:removeEventListener("touch", ScreenTouchListener)
timer.performWithDelay(500, function()
director:changeScene("mainPage") end, 1)
end
end
end
bird1:addEventListener("collision", gotShot)
Runtime:addEventListener("touch", ScreenTouchListener)
---------
-- MUST return a display.newGroup()
return localGroup
end
Any help is appreciated!
The error message is perfectly clear -- the variable sprite used at this line:
local bird1 = sprite.birdSheet( birdSet )
has a nil value, meaning it has not been initialized or was set to nil. You need to show the earlier code where you should have set it up.
(After OP updates)
I think this line
require "sprite"
should actually be
sprite = require "sprite"
You can read more in modules tutorial here:
http://lua-users.org/wiki/ModulesTutorial

Attempt to Index GlobalCredits 'event' (a nil value)

I have just started to learn LUA in school, but i cannot find many helpful tutorials o the internet to aid in my learning. I have made a simple game (which doesn't work yet, i realize that) and a main menu. However, when i try to start the app, it gives me this error:
/Users/jordanmcbride/Desktop/Lua Projects/Tapinator/main.lua:47: attempt to index global 'showCredits' (a nil value)
stack traceback:
/Users/jordanmcbride/Desktop/Lua Projects/Tapinator/main.lua:47: in main chunk
[Finished in 9.4s]
I have looked the error, and I cannot seem to understand how to fix it. The other questions have said something about returning the function returning a nil value, and that I should add a return statement to the end, but that doesn't work either.
Here is the code # line 47.
function showCredits.touch(e)
playButton.isVisible = false
creditsButton.isVisible = false
creditsView = display.newImage('credits.png', 0, display.contentHeight)
lastY = name.y
transition.to(name, {time = 300, y = display.contentHeight * 0.5 - title.height - 25})
transition.to(creditsView, {time = 300, y = display.contentHeight * 0.5 + creditsView.height, onComplete = function() creditsView:addEventListener('tap', hideCredits) end})
end
Here is my full code, in case the problem lies elsewhere:
display.setStatusBar(display.HiddenStatusBar)
radius = 40
smallTime = 200
bigTime = 800
score = 0
scoreInc = 2000
--HomePage
local name
local playButton
local creditsButton
local homePage
--Credits
local creditsPage
--Sounds
local circleSpawn = audio.loadSound( "circle_spawn.wav" )
local circleTap = audio.loadSound( "circle_tap.wav" )
function Main()
name = display.newImage('title.png', display.contentWidth / 2, 53)
name:scale( .5, .5 )
playButton = display.newImage('playButton.png', display.contentWidth / 2, 245)
playButton:scale( .5, .5 )
creditsButton = display.newImage('creditsButton.png', display.contentWidth / 2, 305)
creditsButton:scale( .5, .5 )
homePage = display.newGroup(name, playButton, creditsButton)
startButtonListeners('add')
end
function showCredits.touch(e)
playButton.isVisible = false
creditsButton.isVisible = false
creditsView = display.newImage('credits.png', 0, display.contentHeight)
lastY = name.y
transition.to(name, {time = 300, y = display.contentHeight * 0.5 - title.height - 25})
transition.to(creditsView, {time = 300, y = display.contentHeight * 0.5 + creditsView.height, onComplete = function() creditsView:addEventListener('tap', hideCredits) end})
end
function hideCredits.touch(e)
transition.to(creditsView, {time = 300, y = display.contentHeight, onComplete = function() creditsButton.isVisible = true playButton.isVisible = true creditsView:removeEventListener('tap', hideCredits) display.remove(creditsView) creditsView = nil end})
transition.to(name, {time = 300, y = lastY});
end
function startButtonListeners(action)
if(action == 'add') then
playButton:addEventListener('touch', playGame)
creditsButton:addEventListener('touch', showCredits)
else
playButton:removeEventListener('touch', playGame)
creditsButton:removeEventListener('touch', showCredits)
end
end
Main()
printScore = display.newText("Score: " .. tostring(score), display.contentWidth-80, 40, native.systemFontBold, 20)
-- A function that creates random circles
function generateCircle ()
-- Creates a new circle between 0 (the left most bounds) and the width of the display (being the content width), and also
-- 0 (the upper most bounds) and the height of the display (being the content height). The radius of the circle is 'radius'
x = math.random(radius, display.contentWidth-radius)
y = math.random(80, display.contentHeight)
score = score + scoreInc
myCircle = display.newCircle( x, y, radius )
myCircle:setFillColor( math.random(), math.random(), math.random() )
delayTime = math.random(smallTime, bigTime)
score = score + scoreInc
printScore.text = "Score:"..tostring(scores)
local spawnChannel = audio.play( circleSpawn )
timer.performWithDelay( delayTime, generateCircle )
end
generateCircle()
function myCircle:touch( event )
local tapChannel = audio.play( circleTap )
myCircle:removeSelf()
end
myCircle:addEventListener( "touch", myCircle )
The answer by greatwolf will work. But just a tip from my experience. One way I like to create functions is to try to define the name of the function first near the top of the lua file. Then I will define the function later on in the file. Something like this:
--function preallocation
local onPlayTap
local onSoundOnTap
local onSoundOffTap
local onCreditsTap
local onHelpTap
---------------------------------------------------------------------------------
-- Custom Function Definitions
---------------------------------------------------------------------------------
--Called when Sound On Button is tapped, turn off sound
onSoundOnTap = function(event)
end
--Called when Sound Off Button is tapped, turn on sound
onSoundOffTap = function(event)
end
--Called when Credits button is tapped, shows credits
onCreditsTap = function(event)
end
--Called when Help button is tapped, shows help
onHelpTap = function(event)
end
--Callback to Play button. Moves scene to Level Picker Scene
onPlayTap = function(event)
end
What this does is allow each function to be called by any other function in the file. If you do it the way you are doing it by adding the function name before the function like so:
local showCredits = {}
function showCredits.touch(e)
end
local hideCredits = {}
function hideCredits.touch(e)
end
your showCredit function will not be able to call the hideCredits function below it because the hideCredits variable has not been defined yet when the showCredit function was defined. Although this may not effect your current game, in future apps or games, you may need to call functions inside of other functions. To make this work properly, predefine all your function variables first, then define all your function afterwards. Hope this helps.

How to utilize combo scoring in Corona?

i just have a quick question. Im playing around with Corona to try and get the look and feel of it and im currently editing some one else's sample code. I have added a scoring mechanism, and now i want to add a combo scoring mechanism so that when the user chops more than one fruit, i can add an extra 5 points. Its just that i have no idea how to start. If some one would point me in the right direction that would be great thank you. :)
Or if this would be much clearer: How about a function that will help me detect how many objects the user touches/slices in one touch/move?
require ("physics")
local ui = require("ui")
physics.start()
-- physics.setDrawMode ( "hybrid" ) -- Uncomment in order to show in hybrid mode
physics.setGravity( 0, 9.8 * 2)
physics.start()
-- Audio for slash sound (sound you hear when user swipes his/her finger across the screen)
local slashSounds = {slash1 = audio.loadSound("slash1.wav"), slash2 = audio.loadSound("slash2.wav"), slash3 = audio.loadSound("slash3.wav")}
local slashSoundEnabled = true -- sound should be enabled by default on startup
local minTimeBetweenSlashes = 150 -- Minimum amount of time in between each slash sound
local minDistanceForSlashSound = 50 -- Amount of pixels the users finger needs to travel in one frame in order to play a slash sound
-- Audio for chopped fruit
local choppedSound = {chopped1 = audio.loadSound("chopped1.wav"), chopped2 = audio.loadSound("chopped2.wav")}
-- Audio for bomb
local preExplosion = audio.loadSound("preExplosion.wav")
local explosion = audio.loadSound("explosion.wav")
-- Adding a collision filter so the fruits do not collide with each other, they only collide with the catch platform
local fruitProp = {density = 1.0, friction = 0.3, bounce = 0.2, filter = {categoryBits = 2, maskBits = 1}}
local catchPlatformProp = {density = 1.0, friction = 0.3, bounce = 0.2, filter = {categoryBits = 1, maskBits = 2}}
-- Gush filter should not interact with other fruit or the catch platform
local gushProp = {density = 1.0, friction = 0.3, bounce = 0.2, filter = {categoryBits = 4, maskBits = 8} }
-- Will contain all fruits available in the game
local avalFruit = {}
-- Slash line properties (line that shows up when you move finger across the screen)
local maxPoints = 5
local lineThickness = 20
local lineFadeTime = 250
local endPoints = {}
-- Whole Fruit physics properties
local minVelocityY = 850
local maxVelocityY = 1100
local minVelocityX = -200
local maxVelocityX = 200
local minAngularVelocity = 100
local maxAngularVelocity = 200
-- Chopped fruit physics properties
local minAngularVelocityChopped = 100
local maxAngularVelocityChopped = 200
-- Splash properties
local splashFadeTime = 2500
local splashFadeDelayTime = 5000
local splashInitAlpha = .5
local splashSlideDistance = 50 -- The amoutn of of distance the splash slides down the background
-- Contains all the available splash images
local splashImgs = {}
-- Gush properties
local minGushRadius = 10
local maxGushRadius = 25
local numOfGushParticles = 15
local gushFadeTime = 500
local gushFadeDelay = 500
local minGushVelocityX = -350
local maxGushVelocityX = 350
local minGushVelocityY = -350
local maxGushVelocityY = 350
-- Timer references
local bombTimer
local fruitTimer
-- Game properties
local fruitShootingInterval = 1000
local bombShootingInterval = 5000
-- Groups for holding the fruit and splash objects
local splashGroup
local fruitGroup
local sampleVar = true
local score = 0
local scoreText
function main()
score = 0
display.setStatusBar( display.HiddenStatusBar )
setUpBackground()
scoreText = display.newText("Score: 0", 415, 100, native.systemFont, 50)
scoreText:setTextColor(255, 255, 255)
scoreText.text = ("Score: " )..score
pauseAndResume ()
setUpCatchPlatform()
initGroups()
initFruitAndSplash()
Runtime:addEventListener("touch", drawSlashLine)
timer.performWithDelay( 1000, displayScore)
startGame()
end
function displayScore()
scoreText.text = ("Score: " )..score
score = score + 2
end
function startGame()
shootObject("fruit")
bombTimer = timer.performWithDelay(bombShootingInterval, function(event) shootObject("bomb") end, 0)
fruitTimer = timer.performWithDelay(fruitShootingInterval, function(event) shootObject("fruit") end, 0)
end
-- Display the pause button
function pauseAndResume ()
pausebutton = display.newImage ("paused2.png", 10, 100)
pausebutton:addEventListener ("touch" , pauseGame)
resumebutton = display.newImage ("resume.png", 10, 100)
resumebutton.isVisible = false
resumebutton:addEventListener ("touch", resumeGame)
end
function pauseGame (event)
if (event.phase == "ended") then
physics.pause ()
pausebutton.isVisible = false
resumebutton.isVisible = true
timer.pause(fruitTimer)
timer.pause(bombTimer)
sampleVar = false
return true
end
end
function resumeGame (event)
if (event.phase == "ended") then
physics.start()
pausebutton.isVisible = true
resumebutton.isVisible = false
timer.resume(fruitTimer)
timer.resume(bombTimer)
sampleVar = true
return true
end
end
function initGroups()
splashGroup = display.newGroup()
fruitGroup = display.newGroup()
end
function setUpBackground()
local background = display.newImage("bg.png", true)
background.x = display.contentWidth / 2
background.y = display.contentHeight / 2
end
-- Populates avalFruit with all the fruit images and thier widths and heights
function initFruitAndSplash()
local watermelon = {}
watermelon.whole = "watermelonWhole.png"
watermelon.top = "watermelonTop.png"
watermelon.bottom = "watermelonBottom.png"
watermelon.splash = "redSplash.png"
table.insert(avalFruit, watermelon)
local strawberry = {}
strawberry.whole = "strawberryWhole.png"
strawberry.top = "strawberryTop.png"
strawberry.bottom = "strawberryBottom.png"
strawberry.splash = "redSplash.png"
table.insert(avalFruit, strawberry)
-- Initialize splash images
table.insert(splashImgs, "splash1.png")
table.insert(splashImgs, "splash2.png")
table.insert(splashImgs, "splash3.png")
end
function getRandomFruit()
local fruitProp = avalFruit[math.random(1, #avalFruit)]
local fruit = display.newImage(fruitProp.whole)
fruit.whole = fruitProp.whole
fruit.top = fruitProp.top
fruit.bottom = fruitProp.bottom
fruit.splash = fruitProp.splash
return fruit
end
function getBomb()
local bomb = display.newImage( "bomb.png")
return bomb
end
function shootObject(type)
local object = type == "fruit" and getRandomFruit() or getBomb()
fruitGroup:insert(object)
object.x = display.contentWidth / 2
object.y = display.contentHeight + object.height * 2
fruitProp.radius = object.height / 2
physics.addBody(object, "dynamic", fruitProp)
if(type == "fruit") then
object:addEventListener("touch", function(event) chopFruit(object) end)
else
local bombTouchFunction
bombTouchFunction = function(event) explodeBomb(object, bombTouchFunction); end
object:addEventListener("touch", bombTouchFunction)
end
-- Apply linear velocity
local yVelocity = getRandomValue(minVelocityY, maxVelocityY) * -1 -- Need to multiply by -1 so the fruit shoots up
local xVelocity = getRandomValue(minVelocityX, maxVelocityX)
object:setLinearVelocity(xVelocity, yVelocity)
-- Apply angular velocity (the speed and direction the fruit rotates)
local minAngularVelocity = getRandomValue(minAngularVelocity, maxAngularVelocity)
local direction = (math.random() < .5) and -1 or 1
minAngularVelocity = minAngularVelocity * direction
object.angularVelocity = minAngularVelocity
end
function explodeBomb(bomb, listener)
bomb:removeEventListener("touch", listener)
-- The bomb should not move while exploding
bomb.bodyType = "kinematic"
bomb:setLinearVelocity(0, 0)
bomb.angularVelocity = 0
-- Shake the stage
local stage = display.getCurrentStage()
local moveRightFunction
local moveLeftFunction
local rightTrans
local leftTrans
local shakeTime = 50
local shakeRange = {min = 1, max = 25}
moveRightFunction = function(event) rightTrans = transition.to(stage, {x = math.random(shakeRange.min,shakeRange.max), y = math.random(shakeRange.min, shakeRange.max), time = shakeTime, onComplete=moveLeftFunction}); end
moveLeftFunction = function(event) leftTrans = transition.to(stage, {x = math.random(shakeRange.min,shakeRange.max) * -1, y = math.random(shakeRange.min,shakeRange.max) * -1, time = shakeTime, onComplete=moveRightFunction}); end
moveRightFunction()
local linesGroup = display.newGroup()
-- Generate a bunch of lines to simulate an explosion
local drawLine = function(event)
local line = display.newLine(bomb.x, bomb.y, display.contentWidth * 2, display.contentHeight * 2)
line.rotation = math.random(1,360)
line.width = math.random(15, 25)
linesGroup:insert(line)
end
local lineTimer = timer.performWithDelay(100, drawLine, 0)
-- Function that is called after the pre explosion
local explode = function(event)
audio.play(explosion)
blankOutScreen(bomb, linesGroup);
timer.cancel(lineTimer)
stage.x = 0
stage.y = 0
transition.cancel(leftTrans)
transition.cancel(rightTrans)
end
-- Play the preExplosion sound first followed by the end explosion
audio.play(preExplosion, {onComplete = explode})
timer.cancel(fruitTimer)
timer.cancel(bombTimer)
end
function blankOutScreen(bomb, linesGroup)
local gameOver = displayGameOver()
gameOver.alpha = 0 -- Will reveal the game over screen after the explosion
-- Create an explosion animation
local circle = display.newCircle( bomb.x, bomb.y, 5 )
local circleGrowthTime = 300
local dissolveDuration = 1000
local dissolve = function(event) transition.to(circle, {alpha = 0, time = dissolveDuration, delay = 0, onComplete=function(event) gameOver.alpha = 1 end}); gameOver.alpha = 1 end
circle.alpha = 0
transition.to(circle, {time=circleGrowthTime, alpha = 1, width = display.contentWidth * 3, height = display.contentWidth * 3, onComplete = dissolve})
end
function displayGameOver()
-- Will return a group so that we can set the alpha of the entier menu
local group = display.newGroup()
-- Dim the background with a transperent square
local back = display.newRect( 0,0, display.contentWidth, display.contentHeight )
back:setFillColor(0,0,0, 255 * .1)
group:insert(back)
local gameOver = display.newImage( "gameover.png")
gameOver.x = display.contentWidth / 2
gameOver.y = display.contentHeight / 2
group:insert(gameOver)
local replayButton = ui.newButton{
default = "replayButton.png",
over = "replayButton.png",
onRelease = function(event) group:removeSelf(); main() ; end
}
group:insert(replayButton)
replayButton.x = display.contentWidth / 2
replayButton.y = gameOver.y + gameOver.height / 2 + replayButton.height / 2
return group
end
-- Return a random value between 'min' and 'max'
function getRandomValue(min, max)
return min + math.abs(((max - min) * math.random()))
end
function playRandomSlashSound()
audio.play(slashSounds["slash" .. math.random(1, 3)])
end
function playRandomChoppedSound()
audio.play(choppedSound["chopped" .. math.random(1, 2)])
end
function getRandomSplash()
return display.newImage(splashImgs[math.random(1, #splashImgs)])
end
function chopFruit(fruit)
if (sampleVar == true) then
displayScore()
playRandomChoppedSound()
createFruitPiece(fruit, "top")
createFruitPiece(fruit, "bottom")
createSplash(fruit)
createGush(fruit)
fruit:removeSelf()
end
end
-- Creates a gushing effect that makes it look like juice is flying out of the fruit
function createGush(fruit)
local i
for i = 0, numOfGushParticles do
local gush = display.newCircle( fruit.x, fruit.y, math.random(minGushRadius, maxGushRadius) )
gush:setFillColor(255, 0, 0, 255)
gushProp.radius = gush.width / 2
physics.addBody(gush, "dynamic", gushProp)
local xVelocity = math.random(minGushVelocityX, maxGushVelocityX)
local yVelocity = math.random(minGushVelocityY, maxGushVelocityY)
gush:setLinearVelocity(xVelocity, yVelocity)
transition.to(gush, {time = gushFadeTime, delay = gushFadeDelay, width = 0, height = 0, alpha = 0, onComplete = function(event) gush:removeSelf() end})
end
end
function createSplash(fruit)
local splash = getRandomSplash()
splash.x = fruit.x
splash.y = fruit.y
splash.rotation = math.random(-90,90)
splash.alpha = splashInitAlpha
splashGroup:insert(splash)
transition.to(splash, {time = splashFadeTime, alpha = 0, y = splash.y + splashSlideDistance, delay = splashFadeDelayTime, onComplete = function(event) splash:removeSelf() end})
end
-- Chops the fruit in half
-- Uses some trig to calculate the position
-- of the top and bottom part of the chopped fruit (http://en.wikipedia.org/wiki/Rotation_matrix#Rotations_in_two_dimensions)
function createFruitPiece(fruit, section)
local fruitVelX, fruitVelY = fruit:getLinearVelocity()
-- Calculate the position of the chopped piece
local half = display.newImage(fruit[section])
half.x = fruit.x - fruit.x -- Need to have the fruit's position relative to the origin in order to use the rotation matrix
local yOffSet = section == "top" and -half.height / 2 or half.height / 2
half.y = fruit.y + yOffSet - fruit.y
local newPoint = {}
newPoint.x = half.x * math.cos(fruit.rotation * (math.pi / 180)) - half.y * math.sin(fruit.rotation * (math.pi / 180))
newPoint.y = half.x * math.sin(fruit.rotation * (math.pi / 180)) + half.y * math.cos(fruit.rotation * (math.pi / 180))
half.x = newPoint.x + fruit.x -- Put the fruit back in its original position after applying the rotation matrix
half.y = newPoint.y + fruit.y
fruitGroup:insert(half)
-- Set the rotation
half.rotation = fruit.rotation
fruitProp.radius = half.width / 2 -- We won't use a custom shape since the chopped up fruit doesn't interact with the player
physics.addBody(half, "dynamic", fruitProp)
-- Set the linear velocity
local velocity = math.sqrt(math.pow(fruitVelX, 2) + math.pow(fruitVelY, 2))
local xDirection = section == "top" and -1 or 1
local velocityX = math.cos((fruit.rotation + 90) * (math.pi / 180)) * velocity * xDirection
local velocityY = math.sin((fruit.rotation + 90) * (math.pi / 180)) * velocity
half:setLinearVelocity(velocityX, velocityY)
-- Calculate its angular velocity
local minAngularVelocity = getRandomValue(minAngularVelocityChopped, maxAngularVelocityChopped)
local direction = (math.random() < .5) and -1 or 1
half.angularVelocity = minAngularVelocity * direction
end
-- Creates a platform at the bottom of the game "catch" the fruit and remove it
function setUpCatchPlatform()
local platform = display.newRect( 0, 0, display.contentWidth * 4, 50)
platform.x = (display.contentWidth / 2)
platform.y = display.contentHeight + display.contentHeight
physics.addBody(platform, "static", catchPlatformProp)
platform.collision = onCatchPlatformCollision
platform:addEventListener( "collision", platform )
end
function onCatchPlatformCollision(self, event)
-- Remove the fruit that collided with the platform
event.other:removeSelf()
end
-- Draws the slash line that appears when the user swipes his/her finger across the screen
function drawSlashLine(event)
-- Play a slash sound
if(endPoints ~= nil and endPoints[1] ~= nil) then
local distance = math.sqrt(math.pow(event.x - endPoints[1].x, 2) + math.pow(event.y - endPoints[1].y, 2))
if(distance > minDistanceForSlashSound and slashSoundEnabled == true) then
playRandomSlashSound();
slashSoundEnabled = false
timer.performWithDelay(minTimeBetweenSlashes, function(event) slashSoundEnabled = true end)
end
end
-- Insert a new point into the front of the array
table.insert(endPoints, 1, {x = event.x, y = event.y, line= nil})
-- Remove any excessed points
if(#endPoints > maxPoints) then
table.remove(endPoints)
end
for i,v in ipairs(endPoints) do
local line = display.newLine(v.x, v.y, event.x, event.y)
line.width = lineThickness
transition.to(line, {time = lineFadeTime, alpha = 0, width = 0, onComplete = function(event) line:removeSelf() end})
end
if(event.phase == "ended") then
while(#endPoints > 0) do
table.remove(endPoints)
end
end
end
main()
Try Runtime touch listener ...in that listener event.phase == "move" you can do like above.In event.phase=="ended" reset the value.
Initial set some temp value.
Tempvalue=0
function displayScore()
if Tempvalue == 0 then
Tempvalue=Tempvalue+1
score = score + 2
scoreText.text = ("Score: " )..score
else
score = score + 5
scoreText.text = ("Score: " )..score
end
I just put the sample how to do.
temp=0
local newLine = function(event)
if event.phase=="began" then
elseif event.phase=="moved" then
for i=1,3 do
if event.target.name==i then
temp=temp+1
--here you can do your action to the object(like remove or score)
print("touch"..temp)
end
end
elseif event.phase=="ended" then
end
return true
end
for i=1,3 do
local myCircle = display.newCircle( 100*i, 100, 9 )
myCircle:setFillColor(128,128,128)
myCircle.name=i
myCircle:addEventListener("touch",newLine)
end

Issue with attempted to index a nil variable in lua / corona sdk

I'm pretty new to lua as you can probably tell by the code, i'm trying to remove an object that says "Stop!" when the time runs out by using an event listener on a button object that's also created when the time runs out. This returns the error attempt to index global 'stopit' (a nil value). I declared it as a local var in the class that adds it to the screen so i'm not sure whats going on. I have organized and tried this several different ways and I can't get it to loop continually without randomly crashing either immediately or after one or two rounds of the game.
Here is the code:
display.setStatusBar(display.HiddenStatusBar)
local centerX = display.contentCenterX
local centerY = display.contentCenterY
local score = 0
local dextime;
local stopit;
local button3;
function newTarget(event)
timer.performWithDelay(100, function() display.remove(target) end)
transition.to(target, {time=99, xScale=.4, yScale=.4})
timer.performWithDelay(101, dexit)
score = score + 10
scoreTxt.text = ("Score:" .. score)
end
function dexit()
stopit = display.newImage("stop.png")
stopit.x = 300
stopit.y = 600
stopit.isVisible = false
button3 = display.newImage("button3.png")
button3:addEventListener("tap", removeitems)
button3.x = centerX
button3.y = centerY
button3.isVisible = false
target = display.newImage("target.png")
target.xScale = .25
target.yScale = .25
target.x = math.random(50, 550)
target.y = math.random(50, 750)
target:addEventListener("tap", newTarget)
local function removeitems(event)
stopit:removeSelf()
button3:removeSelf()
scoreTxt:removeSelf()
timerTxt:removeSelf()
timer.performWithDelay(500, setup)
dextime = 15
score = 0
end
timer.performWithDelay(15000, function() display.remove(target) end)
timer.performWithDelay( 15000, function() button3.isVisible = true end)
timer.performWithDelay(15000, function() stopit.isVisible = true end)
end
local function dexgo()
timer.performWithDelay(1000, function() dextime = dextime - 1 end, 15)
timer.performWithDelay(1001, function() timerTxt.text = ("Time:" .. dextime) end, 15)
dexit()
end
local function one2()
local one = display.newImage("1.png")
one.x = centerX
one.y = centerY
one.alpha = 0
transition.to(one, {time=1000, alpha =1, onComplete=dexgo})
timer.performWithDelay( 1000, function()
display.remove(one)
end, 1)
end
local function two2()
local two = display.newImage("2.png")
two.x = centerX
two.y = centerY
two.alpha = 0
transition.to(two, {time=1000, alpha =1, onComplete=one2})
timer.performWithDelay( 1000, function()
display.remove(two)
end, 1)
end
local function dexMode()
local three = display.newImage("3.png")
three.x = centerX
three.y = centerY
three.alpha = 0
timerTxt = display.newText("Time:" .. dextime,-1, centerX - 440, "Helvetica", 40)
scoreTxt = display.newText( "Score:" .. score, 440, -140, "Helvetica", 40)
display.remove(mode1)
display.remove(mode2)
display.remove(title)
transition.to(three, {time=1000, alpha =1, onComplete=two2})
timer.performWithDelay( 1000, function()
display.remove(three)
end, 1)
bg = nil
title = nil
mode1 = nil
mode2 = nil
end
function listener(event)
simpleMode()
end
function listener2(event)
dexMode()
end
function startGame()
transition.to( title, { time=2000, y=0, alpha=.9, onComplete=showTitle})
transition.to(bg, { time=2000, y=centerY, alpha=1})
transition.to(mode1, { time=2000, x=centerX, alpha=.9})
transition.to(mode2, { time=2000, x=centerX, alpha=.9})
end
function setup()
dextime = 15;
bg = display.newImage("background.png")
bg.yScale = 1.4
bg.alpha = 0
title = display.newImage("title.png")
title.x = centerX
title.y = -200
title.alpha = 0
mode1 = display.newImage("button1.png")
mode1.xScale = 1.23
mode1.yScale = 1.23
mode1.x = 800
mode1.y = 500
mode1.alpha = 0
mode2 = display.newImage("button2.png")
mode2.xScale = 1.23
mode2.yScale = 1.23
mode2.x = -200
mode2.y = 625
mode2.alpha = 0
mode1:addEventListener( "touch", listener )
mode2:addEventListener( "touch", listener2 )
startGame()
end
setup()
The usage of in stopit button3, scoreTxt and timerTxt in function removeitems(event) are globally scoped. When removeitems gets called in dexit it cannot see the local variables you declared in dexit.
The easiest solution is to make removeitems a closure by moving it into dexit:
function dexit()
local stopit = display.newImage("stop.png")
local button3 = display.newImage("button3.png")
local function removeitems(event)
stopit:removeSelf()
button3:removeSelf()
scoreTxt:removeSelf()
timerTxt:removeSelf()
timer.performWithDelay(500, setup)
end
-- ...
end
Try this:
if(stopit~=nil)then
stopit:removeSelf()
end
You are getting this error due to timer and transition. When you are removing an object without canceling timer or transition, it's calling in loop and getting nil value after removing once.
First of all you need to store all the timer and transition in array and release array while stoping game or changing scene. Then Reinitialize array again.
Ex: local timerId = {}
local TransitionID = {}
timerId[#timerId+1] = timer.performWithDelay(15000, function() display.remove(target) end)
TransitionID[#TransitionID+1] = transition.to(two, {time=1000, alpha =1, onComplete=one2})
When removing all the object remove timer and transition first.
for i = 1, #timerId do
timer.cancel(timerId[i])
timerId[i] = nil
timerId = {} //Initializing array
end
for j = 1, #transitionID do
transition.cancel(transitionID[j])
transitionID[j] = nil
transitionID = {}
end

Resources