A collection of small utility functions that are commonly repeated in other modules and templates, or are versatile enough to be used in multiple places. Although they could be called into templates the overhead call into Lua would generally be greater than using a built in MediaWiki parser function where one exists.
When calling in to another module, use local util = require( 'Module:Util' )
this will ensure consistency between modules.
Functions
This module consists of four functions.
util.corename()
This function is the only one that can be called directly to other namespaces as well as other Lua functions. By default it looks up the page title it has been transcluded to and truncates any text contained within brackets ()
. If the first parameter has been set iflt will truncate the text within it instead. If needed on an article page, display using {{Pagename nd}}. For calls to templates a direct invocation should be used to reduce overhead.
If being called by another function, the string to be checked should be the second parameter and the first parameter set to nil
. Setting anything to first parameter will cause a code failure as the code expects a frame object here. It is not technically possible to make the frame object the second parameter as invocation always sets the frame object to the first function parameter.
Invocation parameters
The module has no parameters.
util.exists(object, child)
This function checks for results in variables and tables and returns a Boolean. Object
is the variable or table to be checked and the optional
child
parameter is the subitem to check the existence of.
Invocation parameters
This function cannot be invoked.
util.trim(s)
Trims the whitespace (left and right spaces) of a string (s
) passed through. This has been adapted from the trim function on Lua Users to work in mediawiki.
Invocation parameters
This function cannot be invoked.
util.default(data, default)
Takes an object in data
and checks if it exists. If it exists the original object is returned, otherwise the default
is returned.
Invocation parameters
This function cannot be invoked.
local util = {}
function util.corename(frame, title)
if frame ~= nil and util.exists(frame.args[1]) then
result = mw.ustring.gsub(frame.args[1], '%s%(.*', '')
else
if util.exists(title) then
result = mw.ustring.gsub(title, '%s%(.*', '')
else
result = mw.ustring.gsub(mw.title.getCurrentTitle().subpageText, '%s%(.*', '')
end
end
return result
end
function util.exists(object, child)
if object ~= nil and object ~= '' then
if child ~= nil then
if object[child] ~= nil and object[child] ~= '' then
return true
else
return false
end
else
return true
end
else
return false
end
end
function util.trim(s)
return s:match'^()%s*$' and '' or s:match'^%s*(.*%S)'
end
function util.default(data, default)
if util.exists(data) then
return data
else
return default
end
end
return util