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

How do I use string.gsub correctly?

Asked by 4 years ago

I have a string that has the value of a player's name. It was in a table and I converted it correctly using the JSONEncode() function (which is 100% correct). There are two symbols that are left over from the conversion - these square brackets [ ]. I'm trying to use string.gsub to remove them, but it's not working.

Help would be appreciated asap (:

Here is the code below for what I've tried to do with string.gsub:

local finNames = string.gsub(json,'%[', "")
local finXames = string.gsub(finnames,'%]',"")
print(finXames)

1 answer

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

Use JSONDecode() to convert JSON back into a lua table again. Do not bother trying to parse JSON yourself.

Though you should definitely not do this to parse JSON, here's how you would use gsub:

string.gsub(s, pattern, replace)
--for example
print(string.gsub("This is a string!", "string!", "gsub'd string!"))
--returns and prints "This is a gsub'd string!"
print(string.gsub("[This is a string!]", "%[", ""))
--returns and prints "This is a string!]"
0
I managed to get it working with the JSONEncode ( ) as well. Why not try and use it? (I've accepted your answer as it is helpful, thank you!) Primrose_Studio 53 — 4y
0
Thanks as well. You're supposed to use both, JSONEncode for encoding JSON, and then JSONDecode for decoding JSON. Both are very useful for converting between formats. It's impractical to write your own parser because it won't work for all datatypes unless you make it, and Roblox already offers JSONDecode for free. Plus, it's probably faster to use the native function. ArtsicleOfficial 171 — 4y
Ad

Answer this question