Module:MwUtil

local luaUtil = {}

-- Import modules local iter = require("Module:Functional").iter

local GameUIBuilder = require("Module:GameUIBuilder") local Label = GameUIBuilder.GameUILabel

- -- Invoke Wrappers -- - -- Wrapper for all invocations, merging the arguments passed by `#invoke` and the template call -- (with the former taking precedence), trimming leading and trailing whitespaces. -- The function to be wrapped should take a table of arguments instead of the frame object itself. function luaUtil.exportInvoke(func) local function clean(arg) arg = mw.text.trim(arg) if arg == "" then return nil else return arg end end return function(frame) local cleanArgs = iter(pairs(frame:getParent.args)):chain(pairs(frame.args)):map(function (k, v) return k, clean(v) end):tomap return func(cleanArgs) end end

-- Wrapper for UI-related invocations, additionally resulting in a prettier label in the event an error is thrown. local function exportUIInvoke(func) return function(...) local outputs = {pcall(func(...))} local success = table.remove(outputs, 1) if success then return unpack(outputs) else return Label({"game-ui-error-label"}, nil, outputs[1]) end end end luaUtil.exportUIInvoke = luaUtil.exportInvoke(exportUIInvoke)

--- -- Type Checkers -- --- -- Source: https://github.com/wikimedia/mediawiki-extensions-Scribunto/blob/master/includes/engines/LuaCommon/lualib/libraryUtil.lua]] --- -- Raises the error for incorrect type local function raiseError(argIdx, name, expectType, arg) local msg = string.format("bad argument #%d to '%s' (%s expected, got %s)", argIdx, name, expectType, type(arg)) error(msg, 3) end

-- Raises an error if `name` does not have type `expectType` function luaUtil.checkType(name, argIdx, arg, expectType, nilOk) if arg == nil and nilOk then return end if type(arg) ~= expectType then raiseError(argIdx, name, expectType, arg) end end

-- Raises an error if `name` does not have type of any in `expectTypes` function luaUtil.checkTypeMulti(name, argIdx, arg, expectTypes) local argType = type(arg) for _, expectType in ipairs(expectTypes) do		if argType == expectType then return end end local n = #expectTypes local typeList if n > 1 then typeList = table.concat(expectTypes, ', ', 1, n - 1) .. ' or ' .. expectTypes[n] else typeList = expectTypes[1] end raiseError(argIdx, name, typeList, arg) end

return luaUtil