Cant Write or Read my TXT file

I Need my game write and read the “toprecord” on a file, so keep this info btween sesssios.
this is my code… How I make it works?

Thanks

function writefile()
local path = system.pathForFile( “cfl.txt”, system.DocumentsDirectory )
– Open the file handle
local file, errorString = io.open( path, “w” )
if not file then
– Error occurred; output the cause
print( "File error: " … errorString )
else
– Write data to file
file:write( toprecord )
– Close the file handle
io.close( file )
end
file = nil
end
function readfile()
local path = system.pathForFile( “cfl.txt”, system.DocumentsDirectory )
– Open the file handle
local file, errorString = io.open( path, “r” )
if not file then
– Error occurred; output the cause
print( "File error: " … errorString )
else
– Read data from file
local contents = file:read( “*a” )
contents = toprecord
toprecordtxt.text = toprecord
– Output the file contents
print( "Contents of " … path … “\n” … contents )
– Close the file handle
io.close( file )
end
file = nil
end
readfile()

Hello ds.duaarte,

Welcome to the Solar2D community!

Here is a tutorial that may be relevant, https://docs.coronalabs.com/tutorial/data/jsonSaveLoad/index.html

It may not be exactly what you are looking for, but it contains some ideas and snippet codes that you may be able to adapt to use. Most of the time, we use “json type” to keep data like, “high score data”, “user input data”, “most recently used data” and etc, so that we could retrieve them subsequently as a “lua table”.

You may skip the “json.encode” and “json.decode” parts, if you are just keeping your data in “text” or “string type”.

my code was made in part with this tutorial…
I need to know why its not running on device…
ty

Is it working well in Simulator?

Here is a portion of your code above, formatted for read-ability, copied below,

-- Read data from file
local contents = file:read( "*a” )
contents = toprecord
toprecordtxt.text = toprecord

You have just read the latest content of your file as “contents”, why did you over-write your “contents”? Should it not be,

local contents = file:read( "*a" )
toprecordtxt.text = contents

Or, is it a typo-error?

1 Like

it´s working now… thanks a lot