Trying to read from a file

Typically: "How do I... ", "How can I... " questions
Post Reply
abcmeetxyz
Posts: 17
Joined: 19 Feb 2013, 14:13

Trying to read from a file

Post by abcmeetxyz »

Hi,

I've just read a couple of tutorials and stack overflows codes but have not been able to read something from a file.
This is what I'm using so far :

Code: Select all

function file_exists(file)
       local f = io.open(file, "rb")
       if f then f:close() end
	   return f ~= nil
	 end
	 number = 0
     function lines_from(file)
       if not file_exists(file) then return {} end
       lines = {}
       for line in io.lines(file) do 
         lines[#lines + 1] = line
         number = number + 1
       end
     return lines
     end
     file = 'C:\Users\Alex\Desktop\Project\scenes\test.txt'
     lines = lines_from(file)

Eric
Posts: 186
Joined: 11 Feb 2013, 16:39

Re: Trying to read from a file

Post by Eric »

Hi!

Try (3rd line):
if not f then f:close() end

abcmeetxyz
Posts: 17
Joined: 19 Feb 2013, 14:13

Re: Trying to read from a file

Post by abcmeetxyz »

Ty for the quick answer. I've tried fixing that but it did not work so instead I started writing code from the scratch but no matter how I write it the program gets stuck at the io.input or io.open telling me that it can't find my file and I've placed that all over the place. I tried sending as parameter the whole path aswell.
All I need to do is open a txt file and read line by line nothing fancier ....

Cheers,
Alex

nikolaus
Posts: 18
Joined: 13 Feb 2013, 23:17

Re: Trying to read from a file

Post by nikolaus »

Try escaping the backslashes in your file path.
'C:\...' -> 'C:\\...'

Post Reply