Module:Wikitext Parsing: Difference between revisions

Created page with "require("strict") --Helper functions local function startswith(text, subtext) return string.sub(text, 1, #subtext) == subtext end local function endswith(text, subtext) return string.sub(text, -#subtext, -1) == subtext end local function allcases(s) return s:gsub("%a", function(c) return "["..c:upper()..c:lower().."]" end) end local trimcache = {} local whitespace = {[" "]=1, ["\n"]=1, ["\t"]=1, ["\r"]=1} local function cheaptrim(str) --mw.text.trim is surprising..."
 
the Lua # operator recalculates the length every time it's accessed (including on every loop in a for), so cache its value in cheaptrim since the string isn't modified in-place
Line 22: Line 22:
-- local out = string.gsub(str, "^%s*(.-)%s*$", "%1")
-- local out = string.gsub(str, "^%s*(.-)%s*$", "%1")
local lowEnd
local lowEnd
for i = 1,#str do
local strlen = #str
for i = 1,strlen do
if not whitespace[string.sub(str, i, i)] then
if not whitespace[string.sub(str, i, i)] then
lowEnd = i
lowEnd = i
Line 32: Line 33:
return ""
return ""
end
end
for i = #str,1,-1 do
for i = strlen,1,-1 do
if not whitespace[string.sub(str, i, i)] then
if not whitespace[string.sub(str, i, i)] then
local out = string.sub(str, lowEnd, i)
local out = string.sub(str, lowEnd, i)