I need to transfer a text from a text file/string to a Table with a 2 positions vector. Like this:
Text File:
Gustavo 20
Danilo 20
Dimas 40
Table
Names = {{Gustavo,20},{Danilo,20},{Dimas,40}}
Need help to do this.
I need to transfer a text from a text file/string to a Table with a 2 positions vector. Like this:
Text File:
Gustavo 20
Danilo 20
Dimas 40
Table
Names = {{Gustavo,20},{Danilo,20},{Dimas,40}}
Need help to do this.
You can use io.lines()
for this.
vectorarray = {}
for line in io.lines(filename) do
local w, n = string.match(line, "^(%w+)"), string.match(line, "(%d+)$")
table.insert(vectorarray, {w, n})
end
This is, of course, assuming that it's an absolute end of line and absolute start, and there is only those two options per line. If you're using the file name in many other places, then you could set a global variable for the file name and call it each time, such as:
arrayfile = "C:/arrayfile.txt"
Either way, make sure you put the correct path in quotation marks in the file name.
A shorter variation of Josh's answer that directly puts the result into the table. This matches alphabetic names followed by at least one space and numbers but you can change the pattern as needed:
Names = {}
for line in io.lines(filename) do
Names[ #Names+1 ] = {line:match('(%a+)%s+(%d+)')}
end