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

Saving Lines to Table

Started by cdel, 18 February 2015 - 05:05 AM
cdel #1
Posted 18 February 2015 - 06:05 AM
I am parsing some files, and I want to save each line of the file to a separate table entry.
HPWebcamAble #2
Posted 18 February 2015 - 06:14 AM
To save an entire file to a table:


local fTable = {}
local line = 1
f = fs.open("filepath","r")
repeat
  fTable[line] = f.readLine()
  line = line+1
until fTable[line-1] == nil
f.close()

Is that what you're looking for?
Dragon53535 #3
Posted 18 February 2015 - 06:18 AM
To save an entire file to a table:


local fTable = {}
local line = 1
f = fs.open("filepath","r")
repeat
  fTable[line] = f.readLine()
  line = line+1
until fTable[line-1] == nil
f.close()

Is that what you're looking for?

Probably a better way:

local file = fs.open("file","r")
local tbl = {}
local line = file.readLine()
repeat
  table.insert(tbl,line)
  line = file.readLine()
until line == nil
file.close()
cdel #4
Posted 18 February 2015 - 06:31 AM
Thanks, the main concept was me wanting to parse a response from my webserver then further and parse it via cc, the table, for simplicity.
Anavrins #5
Posted 18 February 2015 - 08:19 AM
If I may add

local file = http.get(url)
local tbl = {}
for lineNum, lineContent in file.readLine do
  tbl[#tbl+1] = lineContent
end
Edited on 18 February 2015 - 07:28 AM
Bomb Bloke #6
Posted 18 February 2015 - 09:54 AM
Hmm, I think that might be just:

for lineContent in file.readLine do
HPWebcamAble #7
Posted 19 February 2015 - 12:04 AM
Spoiler
To save an entire file to a table:


local fTable = {}
local line = 1
f = fs.open("filepath","r")
repeat
  fTable[line] = f.readLine()
  line = line+1
until fTable[line-1] == nil
f.close()

Is that what you're looking for?

Probably a better way:

local file = fs.open("file","r")
local tbl = {}
local line = file.readLine()
repeat
  table.insert(tbl,line)
  line = file.readLine()
until line == nil
file.close()

Probably. I think both will work just fine, but yours is shorter.

If I may add

local file = http.get(url)
local tbl = {}
for lineNum, lineContent in file.readLine do --#Maybe for lineContent in file.readLine do?
  tbl[#tbl+1] = lineContent
end

Didn't know that was a thing. Probably works fine too.

Thanks, the main concept was me wanting to parse a response from my webserver then further and parse it via cc, the table, for simplicity.

Ill take that as 'one of these kinda solved my problem'
cdel #8
Posted 19 February 2015 - 12:13 AM
yeah, I decided to use the exact code pretty much, so they could browse previously downloaded messages if they haven't got a stable internet connection.