好吧,讓我們藉此從上而下。首先,它的失敗,因爲你已經有了一個參考錯誤:
...
for k = 1, 3 do
newint = string.sub(mystring, -k*v) -- What is 'mystring'?
end
...
你可能要i
在那裏,不mystring
。
其次,雖然與i
更換mystring
將修復錯誤,它仍然會無法正常工作。
> =reformatint(100)
,100
> =reformatint(1)
,000
這顯然是不正確的。這似乎是你想要做的是通過字符串,並建立與添加逗號的新字符串。但有幾個問題...
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
隨着一些返工,你可以得到一個工作的功能。
function reformatint(integer)
for i = 1, math.floor((string.len(integer)-1)/3) do
integer = string.sub(integer, 1, -3*i-i) ..
',' ..
string.sub(integer, -3*i-i+1)
end
return integer
end
上面的函數似乎工作正常。然而,這相當複雜......可能希望使其更具可讀性。
作爲一個方面說明,一個quick google search發現已經作出了這樣的功能:
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
UFF,我撕開包含從網頁的MyString位,很明顯,我是夠傻忘記掉了這一點。 事實證明,我的谷歌搜索是非常不正確的。 我想感謝你,我將深入探討string.sub()如何操作。我希望迄今爲止我的愚蠢至少會讓我學到一些東西。 – Hultin
@Hultin:不需要看不起自己 - 我們都犯錯誤,而且他們有時候很愚蠢。這就是我們學習的方式。是的,理解'字符串。sub()'是值得的嘗試 - 它實際上與其他語言中的子字符串函數略有不同。另外,歡迎來到StackOverflow! – voithos