-- Converts tabs to spaces
function detab(text)
local tab_width = 4
local function rep(match)
local spaces = -match:len()
print("match:"..match)
while spaces<1 do spaces = spaces + tab_width end
print("Found "..spaces.." spaces")
return match .. string.rep(" ", spaces)
end
text = text:gsub("([^\n]-)\t", rep)
return text
end
str=' thisisa string'
--thiis is a string
print("length: "..str:len())
print(detab(str))
print(str:gsub("\t"," "))
タブをスペースに変換するmarkdown.luaからのこのコードがあります(その名前が示すように)。
私がなんとか理解したのは、文字列の先頭からタブが見つかるまで検索し、一致した部分文字列を'rep'
関数に渡すことです。一致するものがなくなるまで、これを繰り返します。
私の問題は、特にwhileループでrep関数が何をしているのかを理解しようとすることです。
ループが で停止するのはなぜ1
ですか?
なぜカウントアップするのですか?.
驚いたことに、文字列内のスペースの数を数えますが、正確には謎です。
その出力を最後のgsub
置換からの出力と比較すると、それらが異なることがわかります。
Detab は文字の配置を維持しますが、gsub
置換は維持しません。どうしてこんなことに?
ボーナス質問。Scite で空白をオンにすると、 の前の't'
タブが 3 番目の の前のタブよりも長いことがわかります's'
。なぜ違うのですか?