0

I'm trying to write a function that will read sound and music states before starting my application. The problem is: The first time it will run, there will be no data recorded.

First, I tried the suggested JSON function from here and I got this error:

Attempt to call global 'saveTable' (a nil value)

Is there a way to test if the file exists?

Then, I tried this one:

-- THIS function is just to try to find the file.
-- Load Configurations
    function doesFileExist( fname, path )
        local results = false
        local filePath = system.pathForFile( fname, path )

        --filePath will be 'nil' if file doesn,t exist and the path is  "system.ResourceDirectory"
        if ( filePath ) then
            filePath = io.open( filePath, "r" )
        end

        if ( filePath ) then
            print( "File found: " .. fname )
            --clean up file handles
            filePath:close()
            results = true
        else
            print( "File does not exist: " .. fname )
        end

        return results
    end



    local fexist= doesFileExist("optionsTable.json","")

    if (fexist == false) then
        print (" optionsTable = nil")
        optionsTable = {}
        optionsTable.soundOn = true
        optionsTable.musicOn = true
        saveTable(optionsTable, "optionsTable.json")   <<<--- ERROR HERE
        print (" optionsTable Created")
    end

The weird thing is that I'm getting an error at the saveTable(optionsTable,"optionsTable.json"). I just can't understand why.

If you have a working peace of code that handles the first time situation it will be enough to me. Thanks.

4

1 回答 1

1

这是一些检查文件是否存在的代码,您必须先尝试打开文件才能知道它是否存在

function fileExists(fileName, base)
  assert(fileName, "fileName is missing")
  local base = base or system.ResourceDirectory
  local filePath = system.pathForFile( fileName, base )
  local exists = false

  if (filePath) then -- file may exist wont know until you open it
    local fileHandle = io.open( filePath, "r" )
    if (fileHandle) then -- nil if no file found
      exists = true
      io.close(fileHandle)
    end
  end

  return(exists)
end

和使用

if fileExists("myGame.lua") then
  -- do something wonderful
end

您可以参考此链接了解详细信息

于 2013-09-11T05:14:05.510 回答