2017-02-11 27 views
-2

即使我使用GSUB改變白色空間_ if語句仍然得到錯誤企圖指數零值我不知道什麼的疑難問題斜面因爲這是我老師給的指導。使用string.gsub改變白色空間_不工作

這是代碼對不起,我是初學者。

text = "ib c e d f" 
text = string.lower(text) 
b = text:gsub("%s+", "_") 
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 
     print(yes) 
     end 
    end 
+1

什麼是a [i] [2]'? – hjpotter92

回答

0

您的代碼段中存在一些語法錯誤,這會導致您提到的錯誤。 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