I’m somewhat new to parsing Lua strings… can somebody more experienced help me out with this one?
I’m parsing the following string from a text file. I simply want to loop over the string and retrieve each number in turn, each of which will be inserted into another Lua table.
[0,-35,37,30,-37,30]
My best luck so far is this:
for val in string.gmatch(string, "(.-)%,") do
print(val)
end
But this only gets the first 5 values (out of 6) because it’s looking for a full “match” with a comma after every number, and obviously a comma directly follows only the first 5 numbers.
I know there must be a straightforward way to get all 6 values, using a particular pattern match, but the Lua pattern dictation is still throwing a wrench into my brain. If anybody can help, I’d greatly appreciate it!
Patterns are one of the most crazy things to grasp. Even I’m still at a loss without a lot of testing.
Since every number doesn’t have a negative sign, this can throw the pattern matching off, so you have to make sure it’s looking for the “-” AND numbers at the same time. Then since you have multiple digits, you want it to search for this pattern multiple times. Until it reaches the comma.
Take out the period, this is actually a wildcard and it’s very greedy at matching. All you want to search for is the - and number characters. So we put them in [these]. Also since we’re looking for multiples we add a * to the end.
[lua]for val in string.gmatch(string, “([0-9-]*),”) do
print(val)
end[/lua]
You can also try %w instead of 0-9 which will let you get all alphanumeric characters. Since you don’t use any letters, you don’t have to worry about it causing problems.
I haven’t tested it, but this should do it. [import]uid: 11024 topic_id: 4075 reply_id: 12575[/import]
This definitely clears things up, and I’ll certainly find a way to accomplish this now, either using the proper pattern (my pattern was fairly sloppy it seems), or else by using the “split()” function. I appreciate your help with this.
[import]uid: 9747 topic_id: 4075 reply_id: 12617[/import]