How to store file text into array

Questions about the LÖVE API, installing LÖVE and other support related questions go here.
Forum rules
Before you make a thread asking for help, read this.
Post Reply
soytak111
Prole
Posts: 25
Joined: Sat Sep 17, 2022 1:00 am

How to store file text into array

Post 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...
lua,contrary to other language,give you as much space as moon :awesome:
User avatar
darkfrei
Party member
Posts: 1181
Joined: Sat Feb 08, 2020 11:09 pm

Re: How to store file text into array

Post 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
:awesome: in Lua we Löve
:awesome: Platformer Guide
:awesome: freebies
glitchapp
Party member
Posts: 237
Joined: Tue Oct 05, 2021 10:34 am
Contact:

Re: How to store file text into array

Post 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
soytak111
Prole
Posts: 25
Joined: Sat Sep 17, 2022 1:00 am

Re: How to store file text into array

Post 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
lua,contrary to other language,give you as much space as moon :awesome:
Xugro
Party member
Posts: 110
Joined: Wed Sep 29, 2010 8:14 pm

Re: How to store file text into array

Post 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:

Code: Select all

""
But why would you want to do that? You know that you are at the end of the string when

Code: Select all

i == #data[1]
and you are "beyond" the string if

Code: Select all

i == #data[1]+1
There is no need to use

Code: Select all

string.sub(data[1],i,i) == ?
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
Post Reply

Who is online

Users browsing this forum: No registered users and 69 guests