Check out the
fs API for information on how to use the terminal's file system.
If you had a table of numbers, for this example, and you wanted to write it to a file so you could read it back when you restarted your computer, you could do it like this:
-- This function takes a table and writes its contents to the file
-- at the given path.
local function writeTableToFile (myTable, filePath)
-- Get a handle on the file using the fs API so we can write our table to it.
local fileHandle = fs.open (filePath, 'w') -- Use 'w' so we can open the file in 'write' mode.
-- Make sure that we got our file handle successfully so we do not get any errors when
-- trying to write to the file.
if not fileHandle then
return false
end
-- Loop through the table we were given and write each entry to a line in the file.
for index, entry in pairs (myTable) do
fileHandle.writeLine (entry)
end
-- Close the file handle and return from this function.
fileHandle.close()
return true
end
The above code works for a table of numbers, but it would be better to use the
textutils API to serialize the table in case we have other data like strings or other tables within the table we were given.
Now, if you wanted to read this file containing our numbers back into a table, you might do it like this:
-- This function reads each line in a file into a specific entry in a table, then returns the table.
local function readFileIntoTable (filePath)
-- Get a handle on the file in 'read' mode so we can read from it.
-- We use 'io.open' here so we can access the iterator function called 'lines' to
-- iterate over each line in the file without having to worry about going out of bounds.
local fileHandle = io.open (filePath, 'r')
local lines = {} -- This is the table that we'll be reading lines into.
-- Make sure that we got our file handle properly so we don't get any errors
-- when trying to read from it.
if not fileHandle then
return false, nil
end
-- Loop through the file using fileHandle:lines() to read over each line.
-- Record each line in the 'lines' table.
for line in fileHandle:lines() do
table.insert (lines, line)
end
-- Close the file handle and return the table to the calling function.
fileHandle:close()
return true, lines
end
The reason we use the ':' operator instead of the '.' operator in the saving example is because with handles returned by 'io.open' we need to pass the file handle to the function along with any additional arguments. The ':' operator passes the object on the left of it into the function call on the right without us having to specify that.
Again, reading the entire file and then using the
textutils API to unserialize what we read would be a much better way to do this in case you wanted to read in strings or other tables.
Feel free to PM me any questions, or you could ask on this thread and I'll try to reply back if someone doesn't answer your question first. ;)/>