Posted 29 June 2019 - 12:57 PM
Hello!
I don't know how to read from files effectively.
I have used the fh.readLine() function before, but since I didn't have much data to read from I used it a lame way:
As you can see in the readFile() function I use fh.readLine twice in a row. Now I would like to make a program, that reads in more data (probably 10 lines) from a file. I wouldn't like to use ten fh.readLine in a row.
I'm kinda sure that there is an easer, more elegant way of reading data, but how?
Thank you for the help!
eastar
I don't know how to read from files effectively.
I have used the fh.readLine() function before, but since I didn't have much data to read from I used it a lame way:
Spoiler
--To use with Redpower Managers to prevent
--continuous item movement in tubesystem.
fn = "state"
--When no state file exists, info variable
--contains the first state of the tube
local info = {"closed",0}
local cycleCnt = 0
local step = 10 --resolution (in seconds)
--time while tube is closed = Step * maxClosed
local maxClosed = 11
--time while tube is open = Step * maxOpen
local maxOpen = 360
--redstone output for opener motor
tubeOpenerMotor = "left"
--redstone output for closer motor
tubeCloserMotor = "top"
function writeFile(table)
fh = fs.open(fn,"w")
for i=1, #table do
fh.writeLine(tostring(table[i]))
end
fh.close()
end
function readFile()
local table = {}
local cnt = 1
fh = fs.open(fn,"r")
table[1] = fh.readLine()
table[2] = tonumber(fh.readLine())
fh.close()
return table
end
function pushOut()
rs.setOutput(tubeOpenerMotor,true)
sleep(0.5)
rs.setOutput(tubeOpenerMotor,false)
end
function pullIn()
rs.setOutput(tubeCloserMotor,true)
sleep(0.5)
rs.setOutput(tubeCloserMotor,false)
end
if not fs.exists(fn) then
writeFile(info)
else
info = readFile()
end
term.clear()
term.setCursorPos(1,2)
print("Tube-mover is running!")
while true do
if info[1] == "closed" then
term.setCursorPos(2,3)
term.clearLine()
term.write("The tube is closed")
pullIn()
for cycleCnt = info[2], maxClosed do
term.setCursorPos(2,4)
term.clearLine()
term.write("Step: "..cycleCnt.."/"..maxClosed)
sleep(step)
info[2] = cycleCnt + 1
writeFile(info)
end
pushOut()
info[1] = "open"
info[2] = 0
writeFile(info)
end
if info[1] == "open" then
term.setCursorPos(2,3)
term.clearLine()
term.write("The tube is open!")
pushOut()
for cycleCnt = info[2], maxOpen do
term.setCursorPos(2,4)
term.clearLine()
term.write("Step: "..cycleCnt.."/"..maxOpen)
sleep(step)
info[2] = cycleCnt + 1
writeFile(info)
end
pullIn()
info[1] = "closed"
info[2] = 0
writeFile(info)
end
end
As you can see in the readFile() function I use fh.readLine twice in a row. Now I would like to make a program, that reads in more data (probably 10 lines) from a file. I wouldn't like to use ten fh.readLine in a row.
I'm kinda sure that there is an easer, more elegant way of reading data, but how?
Thank you for the help!
eastar