-3

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.

hjpotter92
  • 71,576
  • 32
  • 131
  • 164
  • Welcome to Stack Overflow. When posting questions, you need to explain what you've done to try to solve it. Put in some research. We're here to help, not do everything for you. I've gone ahead and helped you with this one, but you'll continue to get downvotes if you don't put some effort into research. – Josh Apr 20 '15 at 20:27
  • 2
    It's a pity newcomers are 'welcomed' with down votes. Any beginner (in whatever the subject it may be) may have actually put a lot of effort in trying to solve what appears as 'obvious' to most others. Why one has to show unsuccessful (and often 'silly' to the more knowledgeable) attempts just to prove some effort was put in it before coming for help is beyond me. And, what happened to "innocent until proven guilty"? – tonypdmtr Apr 21 '15 at 15:21

2 Answers2

2

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.

Josh
  • 3,053
  • 6
  • 26
  • 43
2

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
tonypdmtr
  • 2,832
  • 2
  • 15
  • 27
  • Ha, I tend to notice such shorter ways much later than intended. Love the compactness! – Josh Apr 21 '15 at 21:53