Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 953
Skuta Avatar asked Dec 11 '09 23:12

Skuta


3 Answers

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.

like image 64
Norman Ramsey Avatar answered Nov 11 '22 23:11

Norman Ramsey


To expand on uroc's answer:

local file = io.open("filename.txt")
if file then
    for line in file:lines() do
        local name, address, email = unpack(line:split(" ")) --unpack turns a table like the one given (if you use the recommended version) into a bunch of separate variables
        --do something with that data
    end
else
end
--you'll need a split method, i recommend the python-like version at http://lua-users.org/wiki/SplitJoin
--not providing here because of possible license issues

This however won't cover the case that your names have spaces in them.

like image 44
RCIX Avatar answered Nov 11 '22 23:11

RCIX


If you have control over the format of the input file, you will be better off storing the data in Lua format as described here.

If not, use the io library to open the file and then use the string library like:

local f = io.open("foo.txt")
while 1 do
    local l = f:read()
    if not l then break end
    print(l) -- use the string library to split the string
end
like image 33
uroc Avatar answered Nov 11 '22 22:11

uroc