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

Why are GSub & GMatch not returning values as supposed to?

Asked by 7 years ago
Edited 7 years ago

Got back on studio to test something (finally) w/ string patterns, which was to see if GSub would replace commas "," w/ "\0", but when I print the result, it just returns "player" in the Output, and not the rest of the string; as for GMatch, it just keeps returning " 2 GMatch Result (x2)" in the Output, and nothing more, so to check if this was the case, I added another table, labeled tableForSeparation, which would gather the items returned, then be unpacked, but nothing in the Output came up; yes, not even nil appeared in the Output.

No errors were returned, so I have no idea how to fix this, and I'm not familiar w/ string patterns, so I have no idea what's going on. This is the code I'm using:


local String = 'player,player2,player3' String = string.lower(String) String = string.gsub(String, '%p', '\0') print(String) -- player local tableForSeparation = {} for i, v in string.gmatch(String, '%z+') do table.insert(tableForSeparation, v or i) print(i or 1, v or 2, 'GMatch Result') -- 2 GMatch Result (x2) end local UnpackTableForSeparation = unpack(tableForSeparation) print(UnpackTableForSeparation) -- [Nothing in Output]

What I was trying to accomplish was to see if the strings between the commas would separate, like how in ACs getPlayer functions where they iterate through a string, then have two tables keep track of the positions from between each string that has a comma.

1 answer

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

Nothing is printing in the output window because you're only matching null characters. In your for loop, string.gmatch is constantly returning the next match it finds given it's string pattern. In this case, your string pattern is %z+, which is only going to match one or more null characters. What you want to do (I'm assuming), is find everything besides null characters. This can be done with complements (represented by the ^ character, in a character set []). Complements will search for a set of characters that don't contain the ones after the compliment. Here's an example:

local str = "player1,player2,player3"

-- Match each string that doesn't contain a comma (i.e, get the characters in between them).
for player in str:gmatch("[^,]+") do
    print(player)
end

-- Output
-- > player1
-- > player2
-- > player3

This also makes the need to use gsub obsolete, since you can use the appropriate pattern directly. Hope I addressed your problem to your satisfaction, if you have any questions, just let me know.

0
Yep, this answered my question! Tyvm! :D Also, nice explanations. :) TheeDeathCaster 2368 — 7y
Ad

Answer this question