Help is appreciated!
Thanks!
Posted 22 February 2013 - 04:29 PM
Posted 22 February 2013 - 06:53 PM
-- 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 endThe 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.
-- 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.0 members, 3 guests, 0 anonymous users