Jump to content
  • Sky
  • Blueberry
  • Slate
  • Blackcurrant
  • Watermelon
  • Strawberry
  • Orange
  • Banana
  • Apple
  • Emerald
  • Chocolate
  • Charcoal

Archived

This topic is now archived and is closed to further replies.

  • 0
Occhioverde

How can I store each line of a file in an array in Lua?

Question

Good morning.
I have a problem with an operation to do in the LUA language:
I have a file in which I have stored data, separated by line. I would need to read this file and store every line of this in an array, ignoring the first one.
For example:

array = {line2, line3, etc}


Next, I would also need to compare each of these lines with a string, to check if it is contained, and I would need to know how to do both.
Thanks in advance for the help.

Share this post


Link to post
Share on other sites

4 answers to this question

Recommended Posts

local file_path = "/home/myFile.txt" -- # path to your file here
local pattern = "match this" -- # your pattern to find
local matches = {}

local function contains(str, pattern)
  return string.match(str, pattern) and true or false
end

for line in io.lines(file_path) do
  if contains(line, pattern) then
    table.insert(matches, line)
  end
end

That should get you started. Feel free to ask more questions if you like :) 

Share this post


Link to post
Share on other sites

It's "Lua", not "LUA".

To read an entire file, use something like this:

image.thumb.png.13993b396d6aa6576f13a9237e04c35c.png

To split it into lines (I could probably do this better with patterns, but it works):

image.png.6476bf0218364e9b234251feaf2a6c38.png

And, looking at PIL, there's a function called table.remove.

"The table.remove function removes (and returns) an element from a given position in an array, moving down other elements to close space and decrementing the size of the array."

So just call table.remove(lines, 1).

That should get you every line from 2 onwards. You should know how to do the rest.

Molinko's solution is simpler, probably faster, and probably also more efficient though.

Share this post


Link to post
Share on other sites
On 25/12/2017 at 12:53 AM, Molinko said:

local file_path = "/home/myFile.txt" -- # path to your file here
local pattern = "match this" -- # your pattern to find
local matches = {}

local function contains(str, pattern)
  return string.match(str, pattern) and true or false
end

for line in io.lines(file_path) do
  if contains(line, pattern) then
    table.insert(matches, line)
  end
end

That should get you started. Feel free to ask more questions if you like :) 

With this solution I managed to solve my problem. Thanks so much.

Share this post


Link to post
Share on other sites

×
×
  • Create New...

Important Information

By using this site, you agree to our Terms of Use and Privacy Policy.