WoWInterface

WoWInterface (https://www.wowinterface.com/forums/index.php)
-   Lua/XML Help (https://www.wowinterface.com/forums/forumdisplay.php?f=16)
-   -   Lua string parsing (https://www.wowinterface.com/forums/showthread.php?t=2354)

Ego 11-08-05 10:36 AM

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.

Littlejohn 11-11-05 03:19 PM

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+)")

Littlejohn 11-11-05 04:18 PM

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)
    local w = { }
    for x in string.gfind(t, "(%d+)") do
        table.insert(w, x)
    end
    return w
end

local n = get_numbers("  1 , 2,3,        4 5-6 ")

print(n[1], n[2], n[3]) -- print first 3 numbers
print(table.concat(n, ", ") .. "\n") -- print all the numbers found


Ego 11-15-05 09:02 PM

Quote:

Originally Posted by Littlejohn
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.

Thanks for the code and advice. I got it working using the gfind() method.
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 04:59 PM.

vBulletin © 2022, Jelsoft Enterprises Ltd
© 2004 - 2021 MMOUI