REMYA
REMYA

Reputation: 29

how to parse strings from a file?

I have a text file. each block parameter is separated by a colon

WoodBlock : 0.886275, 0.607843, 0.25098 : 2, 2, 2 : true : -75.5656891, -11.899992, -416.506866, 1, 0, 0, 0, 1, 0, 0, 0, 1 : 0, 0, 0 : 0, 0, 0

RustedBlock : 0.639216, 0.635294, 0.647059 : 2, 2, 2 : true : -35.5656891, -11.899992, -424.506866, 1, 0, 0, 0, 1, 0, 0, 0, 1 : 0, 0, 0 : 0, 0, 0

StoneBlock : 0.639216, 0.635294, 0.647059 : 2, 2, 2 : true : -50.5656891, -11.899992, -425.506866, 1, 0, 0, 0, 1, 0, 0, 0, 1 : 0, 0, 0 : 0, 0, 0

MetalRod : 0.388235, 0.372549, 0.384314 : 1, 3, 1 : true : -51.5656891, -11.399992, -412.506866, 1, 0, 0, 0, 1, 0, 0, 0, 1 : 0, 0, 0 : 0, 0, 0

Each line contains information about a block. I want to make an algorithm that will work like this:

  1. the first line is selected
  2. the second parameter of the line is selected - the script does something with this parameter
  3. the third parameter of the line is selected - the script does something with this parameter
  4. the fourth parameter of the line is selected - the script does something with this parameter
  5. select the fifth parameter of the line - the script does something with this parameter etc.

I tried using gsub but I don't know how I can select a certain line or parameter in it

Upvotes: 2

Views: 276

Answers (1)

Timmy
Timmy

Reputation: 31

You can use string.gmatch to match all parameters in the colon-delimited string. The pattern used to indicate the separator is [^:]+, which translates to "match everything but : (a colon)".

Here's an example script that loops over each line, then prints each parameter.

for line in io.lines("blocks.txt") do
    for param in string.gmatch(line, "[^:]+") do
        print(param)
    end
end

Upvotes: 3

Related Questions