-- 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'
函数。它会反复执行此操作,直到没有更多匹配项为止。
我的问题是试图弄清楚 rep 函数在做什么,尤其是在 while 循环中。
为什么循环停在1
?
为什么会算上?.
出人意料的是,它统计了字符串中的空格数,究竟如何是个谜。
如果您将其输出与上次gsub
替换的输出进行比较,您会发现它们是不同的。
Detab 保持字符的对齐,而gsub
替换则不保持。为什么呢?
奖金问题。当我在 Scite 中打开空白时,我可以看到 之前的't'
制表符比第三个之前的制表符长's'
。为什么它们不同?