Module:LoadData: Difference between revisions
Jump to navigation
Jump to search
en>MusikBot II m (Protected "Module:LoadData": High-risk template or module: 398 transclusions (more info) ([Edit=Require autoconfirmed or confirmed access] (indefinite))) |
m (1 revision imported) |
(No difference)
|
Latest revision as of 15:50, 17 December 2022
This module is rated as alpha. It is ready for third-party input, and may be used on a few pages to see if problems arise, but should be watched. Suggestions for new features or changes in their input and output mechanisms are welcome. |
A more complex version of Module:Data with more options and the ability to select indexes with an inequality operator.
Usage
{{#invoke:LoadData|Module name|index1|2 lteq=index2 limit|...|}}
- Zeroth parameter is the name of the data module to read, without Module:, e.g.
Example/data
- Next parameters, for an index N starting at one, are called
|N=
for the exact index you need, coerced to number if possible,|N lteq=
to select the highest numerical index less than or equal to the argument, or|N gteq=
for the opposite. |template=
is a printf-style string to interpolate the resulting value(s) into, e.g.<b>%s</b>
.|preprocess=
is like|template=
except thatframe:preprocess
is run on it; this makes e.g. template transclusions work.|if nil=
is the string to return if the result is nil. Default is nil, which comes out as the empty string.
local p = {}
-- Finds the next key key <= or >= the given i.
-- operator is ±1
local function findItemRange(data, i, operator)
local bestIndex = nil
i = i * operator
for k, v in pairs(data) do
local kop = type(k) == 'number' and k * operator
if kop and kop <= i and (bestIndex == nil or kop > bestIndex * operator) then
bestIndex = k
end
end
if bestIndex then return data[bestIndex] else return nil end
end
local function load(datamodule, frame)
local args = frame.args
local data = mw.loadData(datamodule)
for i = 1, 20 do
if args[i] then data = data[tonumber(args[i]) or args[i]]
elseif args[i .. ' lteq'] then
data = findItemRange(data, tonumber(args[i .. ' lteq']), 1)
elseif args[i .. ' gteq'] then
data = findItemRange(data, tonumber(args[i .. ' gteq']), -1)
else break end
end
if data == nil then
return args['if_nil'] -- not a required argument, OK to return nil here.
end
if type(data) == 'table' then
-- Put the table into another table because the return value of loadData
-- is a "fake" table that only has certain metamethods.
local realdata = {}
for k, v in pairs(data) do
realdata[k] = v
end
data = realdata
else
data = { data }
end
if args['template'] then
return mw.text.unstripNoWiki(args['template']):format(unpack(data))
elseif args['preprocess'] then
return frame:preprocess(mw.text.unstripNoWiki(args['preprocess']):format(unpack(data)))
else
return table.concat(data)
end
end
return setmetatable({}, {
__index = function(t, k)
return function(frame)
return load('Module:' .. k, frame)
end
end
})