How to Read a File in Lua

Fri, Oct 28, 2016

Read in 1 minutes

Reading a file in lua is pretty straight forward.

lines = {}

for line in io.lines(arg[1]) do 
  lines[#lines + 1] = line
end

for k,v in pairs(lines) do
  print(k .. ' ' .. v)
end

First create a map for the lines to be placed in. Then for iterate over the files lines using io.lines (we have no error checking here, we just assume it works). We use what we know about reading program arguments to get the filename from the command line.

We place each line in the map using the line number as key.

Finally we print out the pairs in lines having a space between the line number and the actual contents.

See Also

How to Read a File in C#

Tue, Nov 8, 2016

Read more →

How to Read Program Arguments in Lua

Tue, Oct 25, 2016

Read more →

How to Read a File in C++

Tue, Oct 4, 2016

Read more →

How to read a file in Java

Tue, Sep 13, 2016

Read more →

How to Read a file in JavaScript

Fri, Nov 27, 2015

Read more →