Writing data to a text file

Hey guys I am been meaning to learn this for awhile now and have been putting it off but today is the today! I hope I feel retarded but I don’t even know what to search for, I know string.Explode/Implode is used but that’s about all I know. I don’t really know how to create the text file and check and see if it exists and what ever else I need to do. Any input on this would be very much appreciated.

Just what I was looking for thanks man!

[editline]13th June 2013[/editline]

Well if you thought my last post was funny wait until you see this code. I need a little help, here my fail attempt to grab every players steam ID and write it to a text file.



function idkwhatimdoing()

	file.CreateDir( "TESTING" )
	txtFile = file.Write( "TESTING/steamIDs.txt", "" )
	steamIDs = {}
	
	if file.Exists(txtFile, "DATA") then
		steamIDs = string.Explode("
", file.Read(txtFile, "DATA"))
	end
	
	for k, v in pairs(player.GetAll()) do
	table.insert(steamIDs, v:SteamID())
	file.Write(txtFile, string.Implode("
", steamIDs))
	end
end
hook.Add( "Think", "FML", idkwhatimdoing)


If someone could be kind enough to show me how to do this properly I would greatly appreciate it.



concommand.Add("testfiles", function()
    if ( !file.IsDir( "testing", "DATA" ) ) then file.CreateDir( "testing" ) end -- Only try to create a folder if it does not exist
    local filename =  "testing/steam_ids.txt"

    local steamIDs = {}
    for k, v in pairs( player.GetAll() ) do
        table.insert( steamIDs, v:SteamID() ) -- Add all ids to a table
    end

    local towrite = util.TableToJSON( steamIDs ) -- Convert the table to a JSON formatted string
    file.Write( filename, towrite ) -- Write it

    if file.Exists( filename, "DATA" ) then -- Check if file exists
        local str = file.Read( filename, "DATA" ) -- Read the file
        local thetable = util.JSONToTable( str ) -- Convert JSON formatted string back to a table
        PrintTable( thetable ) -- Output the table into console
    end
end )

Untested, but should work. Type testfiles into console to run the code. DO NOT EVER write files in a Think hook.

Don’t use capital letter in file/folder names. It is strongly recommended to use util.TableToJSON and util.JSONToTable functions to save a table to a file.

Works great dude and thanks for the tips/notes, they just made interpreting much faster for me :p. I have two questions:

What does this do give each key a value? Example: FirstEntry[1], SecondEntry[2] instead of FirstEntry, SecondEntry.
local towrite = util.TableToJSON( steamIDs ) – Convert the table to a JSON formatted string

Why does it make a second empty text file called steamIDs.txt?

Thank you very much, I really appreciated you taking the time to help me learn!