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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With