tags:

views:

372

answers:

3

Hi,

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.

+2  A: 

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
uroc
+2  A: 

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.

RCIX
+4  A: 

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.

Norman Ramsey