tabs - How does this detab function in Lua work -
-- converts tabs spaces function detab(text) local tab_width = 4 local function rep(match) local spaces = -match:len() print("match:"..match) while spaces<1 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 string print("length: "..str:len()) print(detab(str)) print(str:gsub("\t"," "))
i have piece of code markdown.lua converts tabs spaces(as name suggests).
what have managed figured out searches beginning of string until finds tab , passes matched substring 'rep'
function. repeatedly until there no more matches.
problem in trying figure out rep function doing in while loop.
why loop stop @ 1
?
why count up?.
suprisingly, counts number of spaces in string, how mystery.
if compare output output last gsub
replacement you'll find different.
detab maintains alignment of characters while gsub
replacement doesn't. why so?
bonus question. when switch on whitespace in scite, can see tab before 't'
longer tab before third 's'
. why different?
to answer bonus question: tab characters align tabstops. tabstop 8 characters. first tab starts on column 6 needs pad 3 spaces. second tab starts on column 16 needs 1 space wide.
the loop stops when spaces becomes positive number because loop has been adding spaces in 'indent' increments until has enough spaces longer matched text. when combines number of spaces matched text has constructed string padded correct tabstop.
that's why gsub differs. gsub isn't treating tabs tabstop characters rather 4 spaces. second tab doesn't pad tabstop instead expands 4 spaces.
Comments
Post a Comment