Module:Utils: Difference between revisions

From Nguhcraft Wiki
Jump to navigation Jump to search
No edit summary
No edit summary
 
(3 intermediate revisions by the same user not shown)
Line 24: Line 24:
end
end


_m.json = function(data)
_m.find = function(tab, field, val)
return '<pre id="jsondata"><nowiki>' .. mw.text.jsonEncode(data) .. '</nowiki></pre>'
for i, v in ipairs(tab) do
if v[field] == val then return i, v end
end
return nil
end
end
return _m
return _m

Latest revision as of 18:11, 5 January 2026

Utility functions to help creating modules

def(value, default)

Returns value if it is not nil or "", and defaultotherwise

_a(arg)

Extracts the argument from the common ways mediawiki passes arguments to modules:
  • if arg is not a table, it is returned as is (Called from Lua like a function)
  • if arg is a table and that table has a args field, arg.args[1] is returned (Called from MediaWiki’s {{#invoke:}} parser function)
  • if arg is a table but doesn’t contain an args field, args[1] is returned (Called with a table as an argument list[1])

date(y, m, d, short = false)

Formats a date.
If short is set to true, uses shortened months name instead of full length month names.

find(tab, field, val)

Locate an entry in a list of table (useful for search through json data)
Parameters
tab: table: the list to search through
field: any: the field in the objects to search by
value: any: the value to match against
Returns
nil, nil if the value wasn't found
index, value: the index at which the match is, and its value

  1. Some mediawiki functions do that, idk why — Annwan
local _m = {}

--- Return a if not `nil` or the empty string, or b otherwise
_m.def = function(a, b)
	return (a ~= nil and a ~= "") and a or b
end
--- Extracts the argument from all the reasonable ways an argument may have been passed
_m._a = function (x)
	if type(x) ~= "table" then
		return x
	end
	-- Did we get a frame
	if type(x.args) == "table" then return x.args[1] end
	-- Also support passing the argument in a table
	return x[1]
end

_m.date = function(y, m, d, short)
	local months
	if short then months = {"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"}
	else months = {"January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"}
	end
	return tostring(d) .. " " .. tostring(months[m]) .. " " .. tostring(y)
end

_m.find = function(tab, field, val)
	for i, v in ipairs(tab) do
		if v[field] == val then return i, v end
	end
	return nil
end
return _m