Page 1 of 1
How to store file text into array
Posted: Tue Oct 17, 2023 12:44 am
by soytak111
I tried a mutliple of way to do it
My goal is to read a file and store line1 in a array at index 1,line2 at index 2 ect...
Re: How to store file text into array
Posted: Tue Oct 17, 2023 1:45 am
by darkfrei
soytak111 wrote: ↑Tue Oct 17, 2023 12:44 am
I tried a mutliple of way to do it
My goal is to read a file and store line1 in a array at index 1,line2 at index 2 ect...
Looks like
https://stackoverflow.com/a/11204889
Use the iterator to iterate each line in file:
Code: Select all
for line in io.lines(file) do
table.insert (lines, line)
end
Re: How to store file text into array
Posted: Tue Oct 17, 2023 6:42 am
by glitchapp
hi, just in case it helps have a look at the function I created for this purpose, it simulates the <br> label of html to separate lines, feel free to use it or tweak it to your needs:
https://codeberg.org/glitchapp/fish-fil ... /About.lua
Re: How to store file text into array
Posted: Tue Oct 17, 2023 8:16 pm
by soytak111
Ok it work but it doesn't seem to left \n
So my question now is...
Exemple:
for line in love.filesystem.lines( "test/wow.txt" ) do table.insert (data, line) end
For i=1,#data[1]+1 do
If string.sub(data[1],i,i) == ? Then
Some code
End
End
...How would i detect when i is out of the string
In other words,what should I put at the ? So the condition is true when it access out of the string
Re: How to store file text into array
Posted: Tue Oct 17, 2023 8:58 pm
by Xugro
soytak111 wrote: ↑Tue Oct 17, 2023 8:16 pm
In other words,what should I put at the ? So the condition is true when it access out of the string
You need to put the following where the
? is:
But why would you want to do that? You know that you are at the end of the string when
and you are "beyond" the string if
There is no need to use
to check for this case.
If you want to keep the newline character
\n at the end of each line then you can just add it before storing the line in the array:
Code: Select all
for line in io.lines(file) do
table.insert (lines, line .. "\n")
end