'How do i get a Text from a File and put it into an Array

So Basically this is the text in the txt file:

hello, school, tommy, house, homemaking

I Want to put it into an Array So it looks like:

Array = {'hello', 'school', 'tommy', 'house', 'homemaking'}

and Not Like:

Array = {'hello, school, tommy, house, homemaking'}
lua


Solution 1:[1]

With Lua 5.4 you can do a combination of load() io.open() and preparing it with three gsub() on the fly to convert the file content...

> array = load("return " .. io.open('text.txt', 'r'):read('*a'):gsub('^.', '{%1'):gsub('.$', '%1}'):gsub('%w+', '"%1"'))()
> print(#array)
5
> print(table.concat(array,'\n'))
hello
school
tommy
house
homemaking

The three gsub() do...

  1. Replacing first sign with: { + first sign
  2. Replacing last sign with: last sign + }
  3. Put all words into: "word"
    So at the end it is ready to convert...
{"hello", "school", "tommy", "house", "homemaking"
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1