Take the 2-minute tour ×

I was wondering how do I get a line into an array with lua in some sort of function

eg. FileToArray("C:/file.txt")?

I know I can use: var = io.open("file") Data = var:read() But it only returns the 1st line, and no other lines.

Anyone know how to fix this or a different way? I'm new to lua and the file system stuff.

share|improve this question
add comment

2 Answers

up vote 5 down vote accepted

You can pass "*a" to read function, it should read the whole file:

local file = io.open("file-name", "r");
local data = file:read("*a")

And if you want to store each line in an array. Like Jane's solution you can use io:lines () - which returns iterator function (each call gives you a new line)

 local arr = {}
 for line in file:lines() do
    table.insert (arr, line);
share|improve this answer
note that it's only "*a" the fact the "*all" works is chance: it only looks at the first 2 characters. –  daurnimator Oct 12 '12 at 13:16
You are absolutely right , I don't know why I wrote '*all' –  tozka Oct 12 '12 at 13:44
even better than using :lines is io.lines("path"). It will close the file in the last iteration. –  daurnimator Oct 13 '12 at 11:08
What is the "rb" in the format for? I know "r" is read mode, but "rb"? –  user1465457 Oct 13 '12 at 11:32
It's supposed to be binary mode, it is not necessary. I think lua must have ignore it. –  tozka Oct 13 '12 at 11:54
show 3 more comments
local file = io.open("c:\\file.txt")
local tbllines = {}
local i = 0
if file then
    for line in file:lines() do
     i = i + 1
     tbllines[i] = line
    error('file not found')

See: http://lua-users.org/wiki/IoLibraryTutorial for more information.

share|improve this answer
add comment

Your Answer

