how to count how many times I clicked my image button * LUA * - lua

I've created hello world text and a clickable button. When I click the button the hello world jumps around randomly.
The problem: I don't know how to get my program to count how many times i've clicked the button.
My progress:
local myHeight = display.contentHeight
local myWidth = display.contentWidth
local topRightHeight = display.newText ("Height "..myHeight, 300 , 40 ,nil,15)
local topRightWidth = display.newText ("Width "..myWidth, 300,60,nil,15)
local redButton = display.newImage ("button.png",0,0)
redButton.x = display.contentWidth -60
redButton.y = display.contentHeight -62.5
local textObj = display.newText ("Hello World",0,0,native.systemFont,18)
textObj: setFillColor(0,250,0)
textObj.x = 40
textObj.y = 30
local number = 0
number = display.newText (number, 30, 30 , native.systemFont, 25)
function moveButtonRandom (event)
textObj.x = math.random(50, display.contentWidth -50)
textObj.y = math.random(50, display.contentHeight -50)
end
redButton: addEventListener ("tap", moveButtonRandom)

You can use flag of int type to count the number of times button clicked.
Initially set flag=0 and if button is clicked then inside onclick() method use flag=flag+1.

Now it works like a charm
display.setStatusBar(display.HiddenStatusBar)
local redButton = display.newImage ("button.png",0,0)
redButton.x = display.contentWidth - 60
redButton.y = display.contentHeight - 62.5
local textObj = display.newText("Hello World", 0, 0, native.systemFont, 18)
textObj:setFillColor(0, 250, 0)
textObj.x = 40
textObj.y = 30
local number = 0
local textField = display.newText(number, 30, 30, native.systemFont, 25)
local function moveButtonRandom(event)
textObj.x = math.random(50, display.contentWidth - 50)
textObj.y = math.random(50, display.contentHeight - 50)
number = number + 1
textField:removeSelf()
textField = display.newText(number, 30, 30, native.systemFont, 25)
end
redButton:addEventListener("tap", moveButtonRandom)

You can track the click on monitoring some flag in your clickListener for button. Maintain a flag increment it whenever you clicked on your button through clickListener. Some thing like this
intialize a variable let say int flagForButton = 0 in your activity
OnClickListener clickListener1 = new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
flagForButton++;
Toast.makeText(MarketSnap.this, String.valueOf(flagForButton), Toast.LENGTH_SHORT).show();
}
};
Set the clickListener on the button. Like this
yourbutton.setOnClickListener(clickListener1);
EDIT
While answering this question the question was tagged with Android. So i have put the code as above. But Now the question is edited and tagged as LUA. So the logic remain same you can increment the flagcount in clickListener Of the the button.

Update text number on every click. No need to delete it and create it again.
local number = 0
local textField = display.newText(number, 30, 30, native.systemFont, 25)
local function updateNumber(n)
textField.text = n
end
local function moveButtonRandom(event)
textObj.x = math.random(50, display.contentWidth - 50)
textObj.y = math.random(50, display.contentHeight - 50)
number = number + 1
UpdateNumber(number)
end
redButton:addEventListener("tap", moveButtonRandom)

Related

Runtime event listener works, but not object (LUA, SUBLIME TEXT 3, CORONA SDK)

Related to a previous topic, helpfully answered by Piglet who directed me to documentation in this question: Using a table in Lua to display text isn't working?... for reference.
Because of how long the project has taken me, I decided to rework a good chunk of the program in order to meet my deadline. I used the documentation's help to properly fix the .text display. However, I should have had a functional changing "vnText" object that I could adjust the text of. However... it only works when I use Runtime event listener, and not the object itself.
While I am perfectly happy using the Runtime event listener to complete my project by the deadline, I would like to know why object:addEventListener didn't work as usual. Is there something I am missing in my code, something that Runtime accomplished that clicking on "textRect" won't?
The line in particular is
Runtime:addEventListener("tap", changePage)
It works perfectly now when I run it. The values are drawn from the table, the command print("change text") is displayed.
The object I tried to use in its place was textRect, which is defined earlier on in the program, a couple tables above. That didn't work to draw the text out and put it in the text. But Runtime did and I, for the life of me, cannot understand why.
HOWEVER, an interesting fact is that when I used textRect, "change text" was printed. But the function didn't change vnText.text...? Which is the whole reason I wrote up the program.
I have scoured documentation and other threads hoping to find an answer to this. The code, however, is much more complicated than my own level, since I'm just a high school student learning from class powerpoints ; right now I'm just searching for an answer as to why Runtime works? And if there is anything I can do to make the object work instead.
Thanks for your help, members of Stack Overflow! You all have helped me to learn tons in the past month.
local store = require( "plugin.google.iap.v3" )
local composer = require("composer")
local scene = composer.newScene()
display.setStatusBar( display.HiddenStatusBar ) -- Removes status bar
coins = 5 --[[variable that defines the number of coins player has in the game. It will be different
in a stand alone game, but as a small app meant to demonstrate function, it's necessary to start off
with a small, defined number in the beginning.]]
local logo = display.newImage("/Images/logo.png", 155, 275) --code for my personal logo, drawn by me.
--Not actually showcased in the video because of time limit.
logo.alpha = 0
local function makeTitleTrue() --this function makes the title true once the logo has been shown and faded out
logo:removeSelf() -- removes logo from screen
print("menu should be TRUE")
titleScreen() -- calls function titleScreen (which is thetitle menu)
end
local function fadeOut()
transition.to(logo, {time = 1000, alpha = 0, onComplete = makeTitleTrue})
end
transition.to(logo, {time = 1000, alpha = 1, onComplete = fadeOut}) -- end of logo code
function titleScreen() -- beginning of title code, which is not managed as a separate scene
title = true
titleImg = display.newImage("/Images/vn_bg.png", 155, 275)
--titleWords = display.newImage("/Images/TitleWords.png", 155, 275)
--particles that flow across the screen as a cool effect. fix to flow towards the upper right corner.
local flare = display.newImage("/Images/flare2.png", 40, 30)
flare.xScale = .5
flare.yScale = .5
local flare2 = display.newImage("/Images/flare2.png", 400, 70)
flare2.xScale = .6
flare2.yScale = .6
local flare3 = display.newImage("/Images/flare2.png", -30, 100)
flare3.xScale = .4
flare3.yScale = .4
local flare4 = display.newImage("/Images/flare2.png", 100, 400)
flare4.xScale = .4
flare4.yScale = .4
local flare5 = display.newImage("/Images/flare2.png", 400, 400)
flare5.xScale = .3
flare5.yScale = .3
local flare6 = display.newImage("/Images/flare2.png", 250, 200)
flare6.xScale = .3
flare6.yScale = .3
local function moveFlare1()
transition.to(flare, {time=2000, x = math.random(-100, 450), y = math.random(-100, 700), onComplete = moveFlare1})
end
local function moveFlare2()
transition.to(flare2, {time=2000, x = math.random(-100, 450), y = math.random(-100, 700), onComplete = moveFlare2})
end
local function moveFlare3()
transition.to(flare3, {time=2000, x = math.random(-100, 450), y = math.random(-100, 700), onComplete = moveFlare3})
end
local function moveFlare4()
transition.to(flare4, {time=2000, x = math.random(-100, 450), y = math.random(-100, 700), onComplete = moveFlare4})
end
local function moveFlare5()
transition.to(flare5, {time=2000, x = math.random(-100, 450), y = math.random(-100, 700), onComplete = moveFlare5})
end
local function moveFlare6()
transition.to(flare6, {time=2000, x = math.random(-100, 450), y = math.random(-100, 700), onComplete = moveFlare6})
end
transition.to(flare, {time=2000, x = math.random(-100, 450), y = math.random(-100, 700), onComplete = moveFlare1})
transition.to(flare2, {time=2500, x = math.random(-100, 450), y = math.random(-100, 700), onComplete = moveFlare2})
transition.to(flare3, {time=2000, x = math.random(-100, 450), y = math.random(-100, 700), onComplete = moveFlare3})
transition.to(flare4, {time=2000, x = math.random(-100, 450), y = math.random(-100, 700), onComplete = moveFlare4})
transition.to(flare5, {time=2000, x = math.random(-100, 450), y = math.random(-100, 700), onComplete = moveFlare5})
transition.to(flare6, {time=2000, x = math.random(-100, 450), y = math.random(-100, 700), onComplete = moveFlare6})
--add options that can when the screen is tapped, tap on an option twice to select
--local newGame_op = display.newImage("", )
--local cont_op = display.newImage("", )
--local coin_op = display.newImage("",)
--local end_op = display.newImage("",)
-- start story
-- continue story
-- coin gambling
-- end game
if (title == true) then
Runtime:addEventListener("tap", sceneVN)
end
--coin_op:addEventListener("tap", coinShop)
end
function forceQuit()
function quit()
os.exit()
end
timer.performWithDelay(1000,quit)
end
function sceneVNChapter2()
return
end
function sceneVN() -- the actual visual novel code itself
display.remove(titleImg)
display.remove(flare)
display.remove(flare2)
display.remove(flare3)
display.remove(flare4)
display.remove(flare5)
display.remove(flare6)
title = false
Runtime:removeEventListener()
page = 0
local coinSheetData =
{
width = 32,
height = 32,
numFrames = 8,
}
local coinimageSheet = graphics.newImageSheet( "/Images/spinning_coin.png", coinSheetData )
local sequenceData =
{
name= "spinning_coin",
start = 1,
count = 8,
time = 1000,
loopCount = 0
}
--the properties of the name plate that can be changed ingame by using ".text" property
local nameOptions =
{
text = "Frankenstein",
x = 165,
y = 450,
width = 310,
font = "Charlesworth.ttf",
fontSize = 22,
align = "left"
}
local bg = display.newImage("/Images/bg4.jpg", 155, 275)
local bust_display = display.newImage( "/Images/f_bust1.png", 155, 223 )
textRect = display.newRect(155, 525, 325, 200)
textRect:setFillColor(.02, .02, .02)
textRect.alpha = .9
local frames = display.newImage("/Images/windowframes_gold.png", 155, 275)
display.newText(nameOptions)
local scriptIntro =
{
[1] = "\"I see. So I\'m supposed to pretend I am\na character in a multi-chapter phone\napp that you\'ve been reading...\"",
[2] = "\"So the purpose of this game is to flirt\nwith me until the meter fills up, and\nyou earn enough coins for a date?\"",
[3] = "\"Then let's see how far you get. Charm\nme by picking the right compliments\nto praise me, my lady.\"",
[4] = "\"When the meter is full, you'll be able\nto ask me on a date to progress the\ngame.\"",
[5] = "\"Let's start the game, then... Can you\ncharm me, the butler of the Raizel\nhousehold?\""
}
vnText = display.newText("\"Good evening. This is a demonstration\nof a visual novel and minigame...\"", 160, 500, "Goudy Old Style Regular.ttf", 17)
vnText.x = 20 ; vnText.y = 495
vnText:setFillColor( 1, 1, 1 )
vnText.anchorX = 0
local function changePage()
page = page + 1
print("change text")
vnText.text = scriptIntro[page]
end
Runtime:addEventListener("tap", changePage)
function choiceGame()
local c_Complimented = {
[1] = "\"Aha... thank you so much. I do my best.\"",
[2] = "\"Ah, please, you flatter me too much! I\ncannot even begin to compare with\nyour praises.\"",
[3] = "\"You're making me blush, my lady. Where\ndid you learn such charm?\"",
[4] = "\"I really don't know what to say... how\nsweet.\""
}
local c_Insulted = {
[1] = "\"Is that really your best attempt at a\nflirt? Pathetic...\"",
[2] = "\"A butler of the Raizel household can\'t\n even begin to contemplate the idea\n of dating you.\"",
[3] = "\"Haha... what a wonderful choice... NOT.\nTry again, darling.\"",
[4] = "\"Such insults are below even your calibre,\n my lady.\""
}
local function optionChosen()
if (compliment == true) then
displayStatus.text = c_Complimented[math.random(1,4)]
else
displayStatus.text = c_Insulted[math.random(1,4)]
end
end
displayStatus = display.newText("Haha... I look forward to your attempts\nat flirting with me.", 160, 500, "Goudy Old Style Regular.ttf", 17)
Runtime:addEventListener("tap", optionChosen)
end -- end of choice game
local function flirtComplete()
local scriptComplete =
{
[1] = "\"Then, seeing as this is a simulation of\n a visual novel dating sim, I have no\n choice but to ask you...\"",
[2] = "\"My lady, would you go on a date with me?\nFrankenstein... butler of the finest noble,\nCadis Etrama di Raizel?\"",
[3] = "\"So, have you made a decision about whether\nyou would like to date yet?\""
}
end
if (coins < 10) then
coinsDigits = 2
else
if (coins > 9) and (coins < 100) then
coinsDigits = 3
else
if (coins > 99) and (coins < 1000) then
coinsDigits = 4
else
if (coins > 999) and (coins < 10000) then
coinsDigits = 5
else
if (coins > 9999) and (coins < 100000) then
coinsDigits = 6
end
end
end
end
end
cooin = display.newSprite(coinimageSheet, sequenceData)
cooin.x = 25
cooin.y = 30
cooin:play()
coinText = display.newText("1", 57 + 4 * coinsDigits, 32, "VCR_OSD_MONO_1.001.ttf", 25)
coinText.text = coins
coinTimer = timer.performWithDelay(2000, cooin, 1)
end
function choiceMade( event ) --the scenes where all the choices are made
if (event.action == "clicked") then
local i = event.index
if (i == 1) then
Runtime:removeEventListener()
titleScreen()
else
if (i == 2) then
system.openURL( "https://www.paypal.com/us/home" )
else
if (i == 3) then
return
end
end
end
end
end -- end of choice scenes
function Outofcoins()
--native alert lack of zero coins
local alertMessage = "Uh oh, looks like you've run out of coins! Would you like to keep flirting, or buy more?"
native.showAlert( "Out of coins!", alertMessage, {"Continue flirting", "Purchase coins", "Exit to Menu"}, choiceMade)
end
function sceneGambleStart()
function earntCoins()
numberEarnt = 0
local coinsGot = display.newImage("/Images/coins_gold.png", 155, 275)
coinsGot.alpha = 0
local function fadeOutCoinsEart()
transition.to(logo, {time = 2000, alpha = 0})
display.remove(coinsGot)
end
local transitionFade = transition.to(logo, {time = 2000, alpha = 1, onComplete = fadeOutCoinsEarnt})
timer.performWithDelay(2000, transitionFade, 1)
coinText.text = coins + numberEarnt
end
end
As your code is, textRect and vnText are both global in scope but scriptIntro is local and declared after textRect. So if you tried to add a tap listener to textRect in which you refer to scriptIntro, it wouldn't work. In fact, all of these variables could be local; just declare them in the right order:
local scriptIntro = ... -- an array of strings
local vnText = display.newText(...
vnText.text = scriptIntro[1]
local n = 1
local textRect = display.newRect(...
function textRect:tap( event )
n = n + 1
if n > #scriptIntro then
n = 1
end
vnText.text = scriptIntro[n]
return true
end
textRect:addEventListener( "tap", textRect )

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.

Corona app's purple background in xCodeSimulator

I have a corona app, with two storyboard scenes (scene1.lua, addDesire.lua).
I show addDesire.lua as an overlay:
function onAddPurchase( event )
if event.phase == "ended" then
local options = {
effect = "fromBottom",
time = 500,
isModal = true,
}
storyboard.showOverlay( "addDesire", options )
end
end
In Corona Simulator everything works, but in xCode simulator a pink background appears in several cases.
1) When addDesire.lua appears after onAddPurchase it looks like:
When it should look like:
2) When I close addDesire.lua (tapping on Cancel button) this appears:
There is something even stranger going on under the hood:
addDesire.lua has 2 textFields and 1 textBox which is created in function scene:createScene( event ). If I comment out the code that creates these objects everything works perfectly.
function scene:createScene( event )
local group = self.view
local centerX = display.contentCenterX
local centerY = display.contentCenterY
local _W = display.contentWidth
local _H = display.contentHeight
local bg = display.newImageRect( "assets/dollar.png", 360, 570 )
bg:toBack()
bg.x, bg.y = _W/2, _H/2
bg:addEventListener( "tap", function() native.setKeyboardFocus(nil); end)
group:insert(bg)
-- Rounded Rect Alpha
roundedRect = display.newRoundedRect( 5, 5, _W*0.9, _H*0.8, 10 )
roundedRect.x, roundedRect.y = centerX, centerY
roundedRect:setFillColor( 0/255, 0/255, 0/255, 170/255 )
group:insert(roundedRect)
-- Label Title
titleLabel = display.newText( "Purchase", 0, 0, "AmericanTypewriter-Bold", 20 )
titleLabel.x, titleLabel.y = centerX, _H*0.15
group:insert(titleLabel)
-- Label Fam
nameLabel = display.newText( "Name", 0, 0, "AmericanTypewriter", 18 )
nameLabel.x, nameLabel.y = centerX, _H*0.20
group:insert(nameLabel)
-- Edit Fam
nameText = native.newTextField(_W/2, _H*0.26, 240, 30)
nameText.font = native.newFont(native.systemFont, 18)
nameText:addEventListener( "userInput", inputListener )
group:insert(nameText)
-- Label Name
descriptionLabel = display.newText( "Description", 0, 0, "AmericanTypewriter", 16 )
descriptionLabel.x, descriptionLabel.y = centerX, _H*0.31
group:insert(descriptionLabel)
-- Edit Name
descriptionText = native.newTextBox(_W/2, _H*0.44, 240, 100)
descriptionText.font = native.newFont(native.systemFont, 14)
descriptionText.isEditable = true
descriptionText:addEventListener( "userInput", inputListener )
group:insert(descriptionText)
-- Label Deposit
costLabel = display.newText( "Cost", 0, 0, "AmericanTypewriter", 16 )
costLabel.x, costLabel.y = centerX, _H*0.57
group:insert(costLabel)
-- Edit Deposit
costText = native.newTextField(_W/2, _H*0.64, 240, 30)
costText.font = native.newFont(native.systemFont, 18)
costText.inputType = "number"
costText.align = "center"
costText:addEventListener( "userInput", inputListener )
group:insert(costText)
-- Button Save & Start game
btnSave = widget.newButton {
width = _W*0.4,
height = 50,
--defaultFile = "buttonDefault.png",
--overFile = "buttonOver.png",
label = "Buy",
onEvent = onSaveData
}
btnSave.x, btnSave.y = _W/2, costLabel.y+150
group:insert(btnSave)
-- Button Cancel
btnCancel = widget.newButton {
width = _W*0.8,
height = 50,
--defaultFile = "buttonDefault.png",
--overFile = "buttonOver.png",
label = "Cancel",
onEvent = onExit,
}
btnCancel.x, btnCancel.y = _W/2, btnSave.y+50
group:insert(btnCancel)
end
What is going on?
The answer is here guys: native.textField

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

how to go back in lua file from another lua file?

I have a menu lua and when i choose 1 of the category (the "songselect" lua) and go back to the menu lua i got this error:
Runtime error
...ocuments\corona projects\singingbeemenu\director.lua:151: attempt to
call field 'unloadMe' (a nil value)
stack traceback:
[C]: in function 'unloadMe'
...ocuments\corona projects\singingbeemenu\director.lua:151: in function
'_listener
'
this is 1 of my category the songselect.lua
module(..., package.seeall)
display.setStatusBar( display.HiddenStatusBar )
function new()
local localGroup = display.newGroup()
local tableView = require("tableView")
local ui = require("ui")
--------------------------------------------------------------------------
local screenOffsetW, screenOffsetH = display.contentWidth - display.viewableContentWidth, display.contentHeight - display.viewableContentHeight
local songList
local backBtn
local detailScreenText
local background = display.newRect(0, 0, display.contentWidth, display.contentHeight)
background:setFillColor(0, 0, 0)
local data = {}
--iPad: setup a color fill for selected items
local selected = display.newRect(0, 0, 50, 50) --add acolor fill to show the selected item
selected:setFillColor(67,141,241,180) --set the color fill to light blue
selected.isVisible = false --hide color fill until neede
-----------------------------------------------
data[1] = {}
data[1].title = "Crazy Song"
data[1].subtitle = "by Bruno Earth"
data[1].image = "note.png"
data[2] = {}
data[2].title = "Enter Sunman"
data[2].subtitle = "by Mentalica"
data[2].image = "note.png"
local topBoundary = display.screenOriginY + 40
local bottomBoundary = display.screenOriginY + 0
songList = tableView.newList{
data=data,
default="listItemBg.png",
over="listItemBg_over.png",
top=topBoundary,
bottom=bottomBoundary,
callback = function( row )
local g = display.newGroup()
local img = display.newImage(row.image)
g:insert(img)
img.x = math.floor(img.width*0.5 + 6)
img.y = math.floor(img.height*0.5)
local title = display.newText( row.title, 0, 0, native.systemFontBold, 16 )
title:setTextColor(0,0,0)
g:insert(title)
title.x = title.width*0.5 + img.width + 6
title.y = 30
local subtitle = display.newText( row.subtitle, 0, 0, native.systemFont, 14 )
subtitle:setTextColor(80,80,90)
g:insert(subtitle)
subtitle.x = subtitle.width*0.5 + img.width + 6
subtitle.y = title.y + title.height + 6
return g
end
}
local function scrollToTop()
songList:scrollTo(topBoundary-1)
end
local navBar = display.newImage("navBar.png")
navBar.x = display.contentWidth*.5
navBar.y = math.floor(display.screenOriginY + navBar.height*0.5)
local navHeader = display.newText("Song Lists", 0, 0, native.systemFontBold, 16)
navHeader:setTextColor(255, 255, 255)
navHeader.x = display.contentWidth*.5
navHeader.y = navBar.y
--Setup the back button
local backToMenu = function(event)
print (event.phase)
if event.phase == 'ended' then
print ("ok")
director:changeScene(event.target.scene, "fade")
print ("back!")
end
end
backBtn = display.newImage("backButton.png")
backBtn.x = math.floor(backBtn.width/2) + backBtn.width + screenOffsetW
backBtn.y = navBar.y
backBtn.scene = "menu"
backBtn:addEventListener("touch", backToMenu)
--backBtn.alpha = 0
local listBackground = display.newRect( 0, 0, songList.width, songList.height )
listBackground:setFillColor(255,255,255)
songList:insert(1,listBackground)
return localGroup
end
is it impossible the go back method in lua?
can anyone can help me and give an idea why i got the error?
thanks in advance...
I got this, i change my director.lua to the latest version...
Try this Lua file to solve your problem.

Resources