Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
0

String.match returning "nil, nil"?

Asked by
Vid_eo 126
4 years ago

I have a table of values, and I am iterating through the table and attempting to separate each value into two parts. The values go like this: "Name | Number". I am trying to use string.match to separate them, but it isn't working.

Script:

for i = 1, #StatsData do
    local pattern = "(%a+)$a?|%s?(%d+)"
    print(StatsData[i])
    local key1, val1 = string.match(StatsData[i], pattern)
    print(key1, val1) --prints "nil, nil"
end

Thank you!

0
try reversing the order u put the statsData[i] and pattern in the string.match() TheluaBanana 946 — 4y
0
Use string.find Tweakified 117 — 4y

1 answer

Log in to vote
1
Answered by 4 years ago
Edited 4 years ago

Namaste it is, dual

First of all, you have to realise 1 thing - string.match() does NOT return 2, 3, 4 or n things. It returns 1 thing. One. This can be found here: https://developer.roblox.com/api-reference/lua-docs/string. "If a match is found, it is returned"

Next, you should use an i,v pair loop. What you're doing now is more efficient than said loop, so yes it's more optimised, however it's evident you don't need this optimisation more than you need readability. I recommend rewriting this loop with an i,v pair loop.

Second, can you give an example of the array's values? Right now I'm using {"dlp | 1", "sin | 2", "viking | 3"}, and my code works with this.

I would also like to mention your pattern has a lot of redundant things, that you're also using wrong. lol(?). I recommend reading more about Lua RegEx/pattern matching on: http://lua-users.org/wiki/PatternsTutorial

Here is some reformatted code I wrote.

local arr = {"dlp | 1", "sin | 2", "viking | 3"}

for _, v in pairs(arr) do -- Use a i, v pair loop. I'm not sure why you're using `[i]`
    local match_name = "(%a+)" -- A `^` at the start of the pattern is not needed as there is only 1 alphanumeric value in the string.
    local match_number = "(%d)" -- A `$` at the end of the pattern is not needed as there is only 1 integer in the string.
    local matched_name, matched_number = string.match(v, match_name), string.match(v, match_number)
    print(matched_name, matched_number) -- Prints what you want.
end

That is all

0
Thanks so much for the detailed answer! Vid_eo 126 — 4y
Ad

Answer this question