Tom Hanson
Tom Hanson

Reputation: 153

Corona Writing a file

I am creating a game and need to write the gamedata to a file. I have the game creating the file if its not there and reading the contents of the file (That I put in manually) but I can not get it to write to the file.

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

That part works. i then move to the next scene and attempt to write something new

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 )

But get the error

mainMenu.lua:43: attempt to index local 'myfile' (a nil value)

I know the file is there in the sandbox, and this code was copied from the corona docs. What am I doing wrong???

Upvotes: 2

Views: 427

Answers (3)

Tom Hanson
Tom Hanson

Reputation: 153

I found the solution. I opened the file to read to see if the file exists. I forgot to close it again before I reopened it in the if statement if the file did exist. I only closed it if it didnt exist.

Upvotes: 0

Krishna Raj Salim
Krishna Raj Salim

Reputation: 7390

The error occurs due to the mistake in your code line:

myFile:close()

So either comment the line as:

--myFile:close()

Or do as below (only if you need):

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

Keep Coding............. :)

Upvotes: 1

iBad
iBad

Reputation: 286

here are two functions I am using

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

Usage:

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

SaveTable(t, "filename.json");

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

Enjoy!

Upvotes: 1

Related Questions