【问题标题】:Corona Writing a file电晕写文件
【发布时间】:2014-09-02 19:43:36
【问题描述】:

我正在创建游戏,需要将游戏数据写入文件。如果文件不存在,我让游戏创建文件并读取文件的内容(我手动输入),但我无法让它写入文件。

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”(一个 nil 值)

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

【问题讨论】:

  • local myfile, err = io.open( path, "w" ) 然后print(err) 看看你遇到了什么错误。
  • 权限被拒绝。所以该文件是由应用程序创建的。此错误发生在模拟器中。我还没有在手机上测试过。

标签: lua save coronasdk


【解决方案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);

享受吧!

【讨论】:

    【解决方案2】:

    由于您的代码行中的错误而发生错误:

    myFile:close()
    

    所以要么将这一行注释为:

    --myFile:close()
    

    或者如下(仅当您需要时):

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

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

    【讨论】:

    • 我正在关闭文件,因为我之前打开过它。然后我以“w”模式重新打开它。我以“r”打开文件以“w”打开后是否不需要关闭文件
    • 您正在条件内写入 'file:close()' --> 没有这样的文件。所以要么你必须在关闭之前创建一个文件,要么只是避免关闭...... :)
    【解决方案3】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-03-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多