How to load text file into sort of table-like variable in Lua?

Skuta picture Skuta · Dec 12, 2009 · Viewed 16.7k times · Source

I need to load file to Lua's variables.

Let's say I got

name address email

There is space between each. I need the text file that has x-many of such lines in it to be loaded into some kind of object - or at least the one line shall be cut to array of strings divided by spaces.

Is this kind of job possible in Lua and how should I do this? I'm pretty new to Lua but I couldn't find anything relevant on Internet.

Answer

Norman Ramsey picture Norman Ramsey · Dec 12, 2009

You want to read about Lua patterns, which are part of the string library. Here's an example function (not tested):

function read_addresses(filename)
  local database = { }
  for l in io.lines(filename) do
    local n, a, e = l:match '(%S+)%s+(%S+)%s+(%S+)'
    table.insert(database, { name = n, address = a, email = e })
  end
  return database
end

This function just grabs three substrings made up of nonspace (%S) characters. A real function would have some error checking to make sure the pattern actually matches.