Module:String: Difference between revisions

From Test Wiki
Content deleted Content added
Fix
m 1 revision imported
 
(2 intermediate revisions by 2 users not shown)
Line 97: Line 97:


--[[
--[[
This function implements that features of {{str sub old}} and is kept in order
This function implements that features of {{subr|s|skip|max}} and
to maintain these older templates.
is kept in order to maintain these older templates.

Uses only numbered paramameters to preserve spaces (caller may trim
whitespaces by passing the parameter explicitly by numbering the
parameters).

Accepts negative values as relative to strng length.

No error is returned if attempting to read past end of string or
before start of string.

Currently does not parse and replace placeholders for nowiki tags.
]]
]]
function str.sublength( frame )
function str.sublength( frame )
local i = tonumber( frame.args.i ) or 0
local s = frame.args[1] or '';
local len = tonumber( frame.args.len )
local skip = tonumber( frame.args[2] ) or 0;
local max = tonumber( frame.args[3] ) or 0;
return mw.ustring.sub( frame.args.s, i + 1, len and ( i + len ) )

local len = mw.ustring.len( s );

-- convert negative values of max and skip as relative to string length
if max < 0 then
max = len + max
end
if skip < 0 then
skip = len + skip
end

-- check boundaries to reduce the requested max
if skip < 0 then -- if before start of string
max = max + skip
skip = 0 -- skip can't underflow now
end
if max > len - skip then -- if past end of string
max = len - skip -- max can't overflow now
end
if max <= 0 then
return '' -- nothing left to return
end

return mw.ustring.sub( s, skip + 1, skip + max )
end
end