I need to use files to store the score of a player but I get an error : main.lua:23: attempt to index global ‘file2’ (a nil value). What should I do? Here’s the code:
–cookie clicker–
background=display.newImageRect(‘background.jpg’,360,570) --display the background
background.x = display.contentCenterX
background.y = display.contentCenterY
file=io.open(‘first.txt’,r) --first.txt contains a value of 0 or 1 depending if you have or haven’t played the game
first=file:read()
if first==0 then --if you haven’t played the game the click counter is 0 and the first.txt file gets value 1
tapCount=0
file1=io.open(‘first.txt’,w)
file:write(1)
else --if you have played the game then read your previous score
file2=io.open(‘score.txt’,‘r’)
tapCount=file2:read()
end
tapCount = 0
tapText = display.newText( tapCount, display.contentCenterX, 20, native.systemFont, 40 ) --display your score
cookie=display.newImageRect(‘cookie.png’,200,200) --display the cookie that you click
cookie.x = display.contentCenterX
cookie.y = display.contentCenterY
a=0
function increment()–when you click the cookie you earn points
file3=io.open(“score.txt”,“w”)
tapCount = tapCount + 1
tapText.text = tapCount
file3:write(a)
--print(a)
end
io.output()
cookie:addEventListener(“tap”,increment) --earn points
PS:Please forgive my bad grammar, English is not my native language
EDIT:
Yes, the problem seemed to be that [lua] tonumber() [/lua] function. Thanks a lot! But now when I click the cookie, the score goes up and then back to 0. I’ll attach the whole project in a zip file.
John