Lua string parsing
I'm looking for a bit of help with parsing a string in Lua.
The pattern I've got is 4 numeric values separated by commas. Something that look like "1, 2, 3, 4" I want to split out each value into 4 separate local variables, for example a, b, c, d. It would be nice if the spaces between them were optional, and something that could handle if less than 4 values are present. I haven't learned enough on parsing strings in Lua, so if anyone can provide some help, I'd appreciate it. |
text = "1, 2, 3, 4"
_, _, a, b, c, d = string.find(text, "(%d+), (%d+), (%d+), (%d+)") That is probably too finicky for use in the real world -- it won't match if there are extra spaces around the commas for example. This allows any number of spaces: _, _, a, b, c, d = string.find(text, "(%d+)%s*,%s*(%d+)%s*,%s*(%d+)%s*,%s*(%d+)") That's getting complicated enough that you may want to build up the pattern string.rep: _, _, a, b, c, d = string.find(text, string.rep("(%d+)%s*,%s*", 3) .. "(%d+)") |
If you're going for something that's quick+easy to enter, you might want to skip the comma separated list idea -- it's kind of programmerish ya know? Here's a little function that just grabs all the numbers out of a string. Some mods seem to be overly picky with chat command syntax. (Flexbar comes to mind...) People might like it if your mod is ultra lazy with the chat syntax.
Code:
function get_numbers(t) |
Quote:
Now just got to package up my mod and get it posted. :) And I went with the no commas in the chat command. Although the code provided will ignore them and other stuff, so I guess it doesn't matter. Thanks, |
All times are GMT -6. The time now is 01:07 PM. |
vBulletin © 2024, Jelsoft Enterprises Ltd
© 2004 - 2022 MMOUI