Module:Yesno and Module:Yesno/sandbox: Difference between pages
(Difference between pages)
imported>MusikAnimal Undid revision 948472533 by [[Special:Contributions/w>Vogone|w>Vogone]] ([[User talk:w>Vogone|talk]]) |
imported>Waddie96 f |
||
| Line 1: | Line 1: | ||
-- | --- Allows for consistent treatment of boolean-like wikitext input. | ||
-- It | --- Uses lookup table, instead of if-elseif-else statement, for efficiency. | ||
-- | |||
-- If your wiki uses non-ASCII characters for any of "yes", "no", etc., you | |||
-- should replace "string.lower" with "mw.ustring.lower" in the | |||
-- following line. NOTE: It is _much_ slower. | |||
local LOWER = string.lower | |||
local TO_NUMBER = tonumber | |||
local TYPE = type | |||
local BOOLEAN_MAP = { | |||
yes = true, y = true, ['true'] = true, t = true, on = true, ['1'] = true, | |||
no = false, n = false, ['false'] = false, f = false, off = false, ['0'] = false | |||
} | |||
return function (value, defaultResponse) | |||
if value == nil then | |||
return nil | |||
end | |||
local valueType = TYPE(value) | |||
if valueType == 'boolean' then | |||
return value | |||
elseif valueType == 'string' then | |||
local lookupResult = BOOLEAN_MAP[LOWER(value)] | |||
if lookupResult ~= nil then | |||
return lookupResult | |||
end | |||
end | |||
-- Numeric check works for both numbers and numeric strings. | |||
local number = TO_NUMBER(value) | |||
if number == 1 then | |||
return true | |||
elseif number == 0 then | |||
return false | |||
end | |||
return defaultResponse | |||
end | end | ||