Jump to content




file2table


2 replies to this topic

#1 alexkar598

  • Members
  • 17 posts

Posted 25 July 2018 - 08:14 PM

small api to load in file into a table

https://pastebin.com/PRy6wHcs

functions:

loadFiles(table,path1,path2,path3,etc) will load in the files to the table

structure:

table will contain other tables accessible via a number those table will contain the following:
each line in the file accessible for by a number content,which is a field containing the whole file

Examples:
table[1][2] will access the second line on the first file
table[3]["content"] will access the whole third file

readFile(path,table) will load a single file into the table



structure:
each line in the file accessible for by a number content,which is a field containing the whole file

Examples:
table[2] will access the second line on the first file
[color=#839496]table["content"] will access the whole third file



do note that the api will NO clear the table before writing

have fun with the api,while you are not obligated to credit me in the api or in a project where said api is used,please do not claim you wrote this api

faq:
q:the table is all messed up
a:you probably didint clear it before running the api again

q:i get file2table.lua:4: attempt to index ? (a nil value)
a:you supplied an invalid path

Edited by alexkar598, 25 July 2018 - 08:24 PM.


#2 SquidDev

    Frickin' laser beams

  • Members
  • 1,409 posts
  • LocationDoes anyone put something serious here?

Posted 25 July 2018 - 08:35 PM

Neat! One small improvement you could make would be to use a for loop to iterate over the lines instead - it makes it a wee bit cleaner:
local index = 1
for l in h.readLine do
  table[index] = l
  index = index + 1
end

It may it'd also be nicer if readFile and loadFiles returned a table instead of mutating their argument. This means you don't have to worry about clearing the rest of the table, and allows you can do something like:
local contents = readFile("foo.lua")
--# Instead of
local contents = {}
readFile("foo.lua", contents)

Edited by SquidDev, 25 July 2018 - 08:35 PM.


#3 Bomb Bloke

    Hobbyist Coder

  • Moderators
  • 7,099 posts
  • LocationTasmania (AU)

Posted 26 July 2018 - 02:43 AM

You could furthermore have the for loop make use of io.lines(), which'd save you from having to open and close your file handles manually:

for l in io.lines(path) do

Also, rather than storing two versions of each file, you might consider:

tbl["content"] = function() table.concat(tbl, "\n") end

tbl.content() would then get you the full string, and would remain up to date even if you modified some of the lines.

Note that you'd need to rename your "table" parameter to something like "tbl" (or whatever else), so as not to override and block access to the pre-existing table API (which contains the "concat" function).





1 user(s) are reading this topic

0 members, 1 guests, 0 anonymous users