您的代碼段中存在一些語法錯誤,這會導致您提到的錯誤。 gsub函數實際上工作得很好。
text = "ib c e d f"
text = string.lower(text)
b = text:gsub("%s+", "_") --> this gsub is working just fine
for k=1, #b do
if not string.sub(b, k,k) or string.sub(b, k,k) ~= " " then
if a[i][2] == string.sub(b, k,k) then --> you didn't assign any table called "a" before --> attempting to index a nil value
print(yes)
end
--> haven't close the "if not string.sub" function with an end
end --> this is the end for the loop "for k"
我只是瘋狂猜你要比較的結果字符串與原來的字符串。因爲你的問題是如此的神祕,我只能給你提供的代碼如下,供大家參考:
text = "ab c d e f "
text = string.lower(text)
output = text:gsub("%s", "_")
for k = 1, #output do
local char = string.sub(output, k, k)
local originalChar = string.sub(text, k, k)
if (originalChar ~= " ") and (char == originalChar) then
print(char .. " --> OK")
end
end
的GSUB模式使用的%s
代替%s+
,使每個空間被轉換爲下劃線,讓簡單的單元測試(CHAR通過字符比較)。代碼片段可用here。
什麼是a [i] [2]'? – hjpotter92