This is a read-only snapshot of the ComputerCraft forums, taken in April 2020.
libraryaddict's profile picture

[Request] A Program Which Reads/writes To A File

Started by libraryaddict, 21 February 2012 - 09:06 AM
libraryaddict #1
Posted 21 February 2012 - 10:06 AM
Im trying to figure out how to read and write to a file but Im finding it very very confusing.
When I follow the lua tutorials or docomention I get tons of nil errors and such.

Could someone place give me code which creates a file on first run, Sets different variables on each line and then can call on each line at will.

So basically.

I run "remember"
That makes a new file "forget"
Inside forget
Remember = "The first"
Always = "Remember"
Gonna = "Hey"

So then I can run some other program.
And fetch the variables.

if Always == "Remember" then os.explode()

I would like to look at the code :)/>/>
Advert #2
Posted 21 February 2012 - 12:37 PM
Here:

local fh = io.open("myFile", "w") -- Open for writing
fh:write("Roses are red,n") -- You need n to add a newline
fh:write("Violets are blue, n")
fh:write("All my Turtles are belong to you.n")
fh:close() -- important to close file handles when you're done with them


local fh = io.open("myFile", "r") -- Open for reading
while true do
local line = fh:read("*l")
if not line then break end -- break if we dont have any more lines
print(line) -- Print the line
end
fh:close()
Espen #3
Posted 21 February 2012 - 12:45 PM
As an added note:
You can optionally read the whole file in one go, like this:

local fh = io.open("myFile", "r") -- Open for reading
local content = fh:read("*a") -- Reads the whole file into a string.
fh:close()
print(content) -- Print the whole file incl. line-breaks.

More info on file:read() and its modes: http://www.lua.org/m...l#pdf-file:read
libraryaddict #4
Posted 21 February 2012 - 02:58 PM
Thanks alot guys