3
votes

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.

2

2 Answers

19
votes

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 file = io.open("file-name", "r");
 local arr = {}
 for line in file:lines() do
    table.insert (arr, line);
 end
3
votes
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
    end
    file:close()
else
    error('file not found')
end

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