local formatted
function comma_value(amount)
local formatted = amount
while k ~= 0 do
formatted,k = string.gsub(formatted ,"(-?%d+)(%d%d%d)","%1,%2")
return formatted,k
end
end
comma_value(9999999)
wait(3)
print(formatted,k)
without the loop, it returns properly (9999,999) however, I wanted the loop to continue to add a comma every 3 digits. When I add a print inside the loop, it prints it correctly, but in the end, it returns nil, and k = 0.
You define local formatted outside the function with a nil value and then define another variable that is local inside the function. Because there is a new local variable initialized inside the function, it cannot see it and instead prints the nil version of the variable above the function. If you want to define it again inside the function, you would need to do local formatted, k = comma_value. Either that or remove local from formatted inside the function but this can cause unwanted issues when running the function multiple times.
function comma_value(amount)
local formatted = amount
local k = 1 --Not sure what you want it as?
while k ~= 0 do
formatted,k = string.gsub(formatted ,"(-?%d+)(%d%d%d)","%1,%2")
end
return formatted,k
end
local formatted, k = comma_value(9999999)
wait(3)
print(formatted,k)
EDIT: You also put the return statement inside the loop. That means it returns after the first time it loops. Put it outside when it breaks. Also, I tested and it gave the intended output. Return statement placement can be tricky sometimes, but it happens to the best of us. Good luck!