Replace all negitive numbers in a string with 0,1, or 2

Heyo, I’m a new-ish scripter on Lua and im trying to figure out how to make this script.

Here is what kind of string im dealing with, “-131|-315|132167,-97|-269” my goal is to make this string into something like this : “0|2|132167,1|0” with the 0,1 and 2 being randomly picked.

I’ve tried a very far fetched way of doing it but I can’t figure out how im possibly going to do it. Here is what I sort of have:

 local nums = {0,1,2}
 local song = "-131|-315|132167,-97|-269"
 for i=1,#song do
 	local l = string.sub(song,i,i)
 	if l == "-" then 
 		print(i)
 		song = song:gsub(l,"")
 	end
 	local ye = true
 	local z = string.match(song,"%d+") 
 	local b = nums[math.random(1, #nums)]
 	if #z <= 3 then
 		for i,v in pairs(nums) do
 			if z == v then
 				ye = false
 			else
 				ye = true
 			end
 		end
 		if ye then
 			song = song:gsub(z,b)
 		end
 	end
 end
 print(song)

This is what it outputs:

2|325|232267,97|269

any help is appreciated!

Use string.split to split the string using the “|” operator, then check if its less than 0 then replace it with a random number.

1 Like

Tysm! Here is the code I used that worked for me.. Its a little messy tho.
local nums = {0,1,2}

local song = "-131|-315|132167,-97|-269"

local split = song:split("|")

local s2 = {}

for i,v in pairs(split) do

table.insert(s2,v:split(","))

end

for i,v in pairs(s2) do

for i,v in pairs(v) do

if tonumber(v) < 0 then

song = song:gsub(v,nums[math.random(1, #nums)])

end

end

end

print(song)

Output:
2|2|132167,1|0

Here’s what I would consider a cleaner alternative.

local song = "-131|-315|132167,-97|-269"
local new_song

new_song = song:gsub('%-%d+', function() return math.random(0, 2) end)

print(new_song)

There’s no need to split the string when you’re looking for just whole numbers which may be negative.

If you match your numbers using the string pattern %-%d+, it’ll have gsub find all of the substrings which start with a - sign and are followed by 1 or more digits. This easily matches only whole negative numbers, and then you can pass a function to gsub that gets called for every match so that you return a random number 0 through 2.

I do also suggest however that you store this kind of data in tables instead of strings to begin with, since they’re easier to manipulate.

1 Like

Thanks! Works way better than mine, and also more simple.