Corona 写入文件

我正在创建一个游戏,需要将游戏数据写入文件。如果文件不存在,我已经让游戏去创建文件,可以读取文件的内容(我手动放入的),但我无法将游戏数据写入文件。

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: attempt to index local 'myfile' (a nil value)

我知道这个文件在沙盒中,而且这段代码是从 coronadoc 中复制的。我做错了什么?

点赞
用户1376249
用户1376249

这里有两个我正在使用的函数:

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
         -- 读取文件中的所有内容到一个字符串中
         local contents = file:read( "*a" )
         myTable = JSON.decode(contents);
         io.close( file )
         return myTable
    end
    return nil
end

用法:

local t = {
    text = "一些文本",
    v = 23
};

SaveTable(t, "文件名.json");

local u = LoadTable("文件名.json");
print(u.text);
print(u.v);

享受吧!

2014-09-02 02:27:12
用户1979583
用户1979583

错误发生在代码行中的错误:

myFile:close()

因此,要么将该行注释掉:

- myFile:close()

要么按照以下步骤执行(仅在需要时):

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

继续编码........... :)

2014-09-02 08:47:58
用户2338463
用户2338463

我找到了解决方案。我打开文件进行阅读以查看文件是否存在。我忘记在 if 语句中重新打开它时再次关闭它,如果文件存在的话。如果文件不存在,我只关闭了它。

2014-09-02 11:43:36