Module:Util: Difference between revisions
Jump to navigation
Jump to search
>OmegaK2 (shorthand for abbr added) |
>OmegaK2 m (shorthand for getting current frame) |
||
Line 74: | Line 74: | ||
return tostring(tag) | return tostring(tag) | ||
end | |||
util.misc = {} | |||
function util.misc.get_frame(frame) | |||
if frame == nil or type(frame) == 'table' then | |||
frame = mw.getCurrentFrame() | |||
end | |||
return frame | |||
end | end | ||
return util | return util |
Revision as of 06:18, 1 September 2015
This is a meta module.
This module is meant to be used only by other modules. It should not be invoked in wikitext.
Overview
Provides utility functions for programming modules.
Structure
Group | Description |
---|---|
util.cast | utilities for casting values (i.e. from arguments) |
util.html | shorthand functions for creating some html tags |
util.misc | miscellaneous functions |
Usage
This module should be loaded with require()
.
The above documentation is transcluded from Module:Util/doc.
Editors can experiment in this module's sandbox and testcases pages.
Subpages of this module.
Editors can experiment in this module's sandbox and testcases pages.
Subpages of this module.
-- Utility stuff
local util = {}
util.cast = {}
util.cast.bool_false = {'false', '0', 'disabled', 'off', 'no', ''}
function util.cast.boolean(value)
-- Takes an abitary value and casts it to a bool value
--
-- for strings false will be according to util.cast.bool_false
local t = type(value)
if t == 'nil' then
return false
elseif t == 'boolean' then
return value
elseif t == 'number' then
if t == 0 then return false end
return true
elseif t == 'string' then
local tmp = string.lower(value)
for _, v in ipairs(util.cast.bool_false) do
if v == tmp then
return false
end
end
return true
else
error('"' .. value .. ' is of uncaptured type "' .. t .. '"')
end
end
function util.cast.number(value, default)
-- Takes an abitary value and attempts to cast it to int
--
-- For strings: if default is nil and the conversion fails, an error will be returned
local t = type(value)
if t == 'nil' then
return 0
elseif t == 'boolean' then
if value then
return 1
else
return 0
end
elseif t == 'number' then
return value
elseif t == 'string' then
val = tonumber(value)
if val == nil then
if default ~= nil then
return default
else
error('"' .. value .. '" is not an integer')
end
else
return val
end
else
error('"' .. value .. ' is of uncaptured type "' .. t .. '"')
end
end
util.html = {}
function util.html.abbr(abbr, text, class)
tag = mw.html.create('abbr')
tag
:attr('title', text or '')
:attr('class', class or '')
:wikitext(abbr or ' ')
:done()
return tostring(tag)
end
util.misc = {}
function util.misc.get_frame(frame)
if frame == nil or type(frame) == 'table' then
frame = mw.getCurrentFrame()
end
return frame
end
return util