Module:MW.text

From Touhou Wiki
Jump to navigation Jump to search
Module documentation[view] [edit] [history] [purge]

This library is used only to fix some Scribunto bugs in special cases.
eg. If the built-in mw.text.split crashes lua interpreter, try using the one from this module.

split(text, separator)[edit]

split is opposite function to table.concat.
The separator is a pattern, so any of the magic characters ^$()%.[]*+-? should be escaped with a % when not used as element of pattern.
All the table elements are trimmed.

string.explode('This is a test', ' ')
string.explode('This -=- is -=-\na -=- test', '%-=%-')
string.explode('This 0 is 1 a 2 test', '%d') -- %d means "any digit"
-- will return a table
{'This', 'is', 'a', 'test'}

table.concat(string.explode('Another test string.', ' '), '*foo*')
-- will return a string
'Another*foo*test*foo*string.'
-- though usage of string.gsub is preferred

For more advanced example involving parsing of page content, see sclist and its talk page at Polish Touhou Wiki.

string.trim(str)[edit]

Removes any preceding and trailing whitespace characters from string. Useful when using unnamed parameters for comparison. Named parameters don't require trimming.

{{#invoke:Some script|func
| Value 1
| Value 2
| named1 = Value 3
|...
{{#invoke:Some script|func|Value 1|Value 2|named1=Value 3|...

Both calls can produce different results!
Assuming that f1 and f2 are frame objects of both calls:

f1.args[1] == f2.args[1] -- false
f1.args[2] == f2.args[2] -- false
f1.args['named1'] == f2.args['named1'] -- true
-- This is just a helper library that implements some missing features from current Scribunto release

local common = require("Module:Common")

text = {}

function text.trim(val)
  return tostring(val):gsub("^%s*(.-)%s*$", "%1")
end

function text.split(str, sep, lit)
  local pos = 1
  local t = {}
  if not common.isset(sep) or not common.isset(str) then return t end
    for s, e in function() return string.find(str, sep, pos) end do
    t[#t+1] = text.trim(string.sub(str, pos, s-1))
    pos = e+1
  end
  t[#t+1] = text.trim(string.sub(str, pos))
  return t
end

return text