Totalys
Totalys

Reputation: 465

Corona reading and writing files (first time access)

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.

Upvotes: 0

Views: 529

Answers (1)

DevfaR
DevfaR

Reputation: 1616

here's some code to check if the file exist you have to try and open the file first to know if it exist

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

and for usage

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

you can refer to this link for details

Upvotes: 1

Related Questions