【发布时间】:2013-12-04 02:27:46
【问题描述】:
我正在尝试创建一个使用 json 保存高分的游戏。但我遇到了麻烦。我的一个朋友帮我设置了 json。如果他们以前从未玩过或者如果他们已经击败了他们的高分,它应该保存高分,并将它在控制台上打印出来。但它似乎并没有保存分数,因为它一直返回 nil 并显示当前分数。本节的代码如下。提前致谢。
local json = require("json")
function saveTable(t, filename)
local path = system.pathForFile( filename, system.DocumentsDirectory)
local file = io.open(path, "w")
if file then
local contents = json.encode(t)
file:write( contents )
io.close( file )
return true
else
return false
end
end
function loadTable(filename)
local path = system.pathForFile( filename, system.DocumentsDirectory)
local contents = ""
local myTable = {}
local file = io.open( path, "r" )
if file then
local contents = file:read( "*a" )
myTable = json.decode(contents);
io.close( file )
return myTable
end
return nil
end
myGameSettings = {}
highscore = myGameSettings.highScore
if(highscore == nil)then
highscore = score
myGameSettings.highScore = highscore
print("score was nil")
end
if(highscore < score)then
highscore = score
myGameSettings.highScore = highscore
print ("highscore beaten")
end
displayHighScoreNumber = display.newText("Your score: ", 160, 150,
native.systemFontBold, 40 )
displayHighScoreNumber.text = highscore
displayingHighScore = 1;
myGameSettings = loadTable("mygamesettings.json")
【问题讨论】: