Ok, letβs take it top to bottom. First of all, it does not work, because you have a reference error:
... for k = 1, 3 do newint = string.sub(mystring, -k*v) -- What is 'mystring'? end ...
Most likely you want i
be there, not mystring
.
Secondly, when replacing mystring
with i
, errors will be fixed, it will still work incorrectly.
> =reformatint(100) ,100 > =reformatint(1) ,000
This is clearly not the case. It seems that what you are trying to do is go through the line and create a new line with a comma added. But there are a couple of problems ...
function reformatint(i) local length = string.len(i) for v = 1, math.floor(length/3) do for k = 1, 3 do -- What is this inner loop for? newint = string.sub(mystring, -k*v) -- This chops off the end of -- your string only end newint = ','..newint -- This will make your result have a ',' at -- the beginning, no matter what end return newint end
With some refinement, you can get a function that works.
function reformatint(integer) for i = 1, math.floor((string.len(integer)-1) / 3) do integer = string.sub(integer, 1, -3*ii) .. ',' .. string.sub(integer, -3*i-i+1) end return integer end
The above function is working correctly. However, it is rather confusing ... Could make it more readable.
As an additional note, a quick Google search finds a function that has already been done for this:
function comma_value(amount) local formatted = amount while true do formatted, k = string.gsub(formatted, "^(-?%d+)(%d%d%d)", '%1,%2') if (k==0) then break end end return formatted end