2014-09-02 51 views
2

我正在创建一个游戏,并需要将gamedata写入文件。我有游戏创建文件,如果它不在那里,并阅读文件的内容(我手动),但我无法得到它写入文件。电晕写文件

local path = system.pathForFile("gameData.gameData", system.DocumentsDirectory) 
local myFile 
defaultGameData = "It Worked" 
if (path) then 
    myFile = io.open(path, "r") 
end 

if(myFile) then 
    print('file') 
else 
    myFile:close() 
    --io.close(myFile) 
    myFile = io.open(path, 'w') 
    myFile:write("My Test") 
    io.close(myFile) 
end 

myFile = nil 

该部分起作用。我然后移动到下一个场景,并尝试写一些新的东西

local saveData = "My app state data" 
local path = system.pathForFile("gameData.gameData", system.DocumentsDirectory) 
local myfile = io.open(path, "w") 
myfile:write(saveData) 
io.close(myfile) 

但得到的错误

mainMenu.lua:43:试图指数当地的“MYFILE”(一个零值)

我知道该文件存在于沙盒中,并且此代码是从corona文档复制的。我究竟做错了什么???

+2

'local myfile,err = io.open(path,“w”)'然后'print(err)'看看你得到了什么错误。 – 2014-09-02 01:00:50

+0

权限被拒绝。所以这个文件是由应用程序创建的。这个错误发生在模拟器中。我还没有在手机上测试过。 – 2014-09-02 11:39:22

回答

0

我找到了解决方案。我打开文件来阅读文件是否存在。如果文件确实存在,我在if语句中重新打开它之前忘记再次关闭它。如果它不存在,我只关闭它。

1

这里是我使用

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, dir) 
    if (dir == nil) then 
     dir = system.DocumentsDirectory; 
    end 

    local path = system.pathForFile(filename, dir) 
    local contents = "" 
    local myTable = {} 
    local file = io.open(path, "r") 
    if file then 
     -- read all contents of file into a string 
     local contents = file:read("*a") 
     myTable = JSON.decode(contents); 
     io.close(file) 
     return myTable 
    end 
    return nil 
end 

使用两种功能:

local t = { 
    text = "Sometext", 
    v = 23 
}; 

SaveTable(t, "filename.json"); 

local u = LoadTable("filename.json"); 
print(u.text); 
print(u.v); 

享受!

1

错误的发生是由于在你的代码行的错误:

myFile:close() 

因此,无论评论的路线为:

--myFile:close() 

或者像下面这样做(如果只有需要):

myFile = io.open(path, 'w') 
myFile:close() 

保留编码............. :)

+0

我正在关闭文件,因为我之前打开过它。然后我以“w”模式重新打开它。当我打开它为“r”打开为“w”后,我不需要关闭文件。 – 2014-09-02 10:11:57

+0

您正在条件 - >中写入'file:close()',没有这样的文件。所以要么在关闭之前创建文件,要么避免关闭...... :) – 2014-09-02 18:12:41