【发布时间】:2013-08-01 10:54:07
【问题描述】:
-- 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'。 它们为什么不同?
【问题讨论】:
-
函数
rep(match)中的spaces计算的等效形式没有循环:local spaces = tab_width - #match % tab_width