Module:Recipes/test

-- Note: for "Any xxx" group (e.g. "Any Birds"), they should be added to database. local l10n_info = { ['en'] = { -- for -- ['cate_unexcepted_rows_count'] = 'Recipes table with unexcepted total number of rows', ['cate_no_row'] = 'Recipes table with no row', ['header_result'] = 'Result', ['header_ingredients'] = 'Ingredients', ['header_station'] = 'Crafting station',

['cate_craftable'] = 'Craftable items',

['station_by_hand'] = 'By Hand', ['station_sep_or'] = " or ", ['station_sep_and'] = " and ",

['ingredients_sep'] = " or ", ['snow_biome'] = 'Snow biome',

['station_cate'] = { ['Lead Anvil'] = 'Iron or Lead Anvil', ['Iron Anvil'] = 'Iron or Lead Anvil', ['Orichalcum Anvil'] = 'Mythril or Orichalcum Anvil', ['Mythril Anvil'] = 'Mythril or Orichalcum Anvil', ['Demon Altar'] = 'Demon or Crimson Altar', ['Crimson Altar'] = 'Demon or Crimson Altar', ['Altar'] = 'Demon or Crimson Altar', ['Titanium Forge'] = 'Adamantite or Titanium Forge', ['Adamantite Forge'] = 'Adamantite or Titanium Forge', ['Cauldron'] = 'Cooking Pot or Cauldron', ['Cooking Pot'] = 'Cooking Pot or Cauldron', ['Bottle only'] = 'Placed Bottle', ['Placed Bottle only'] = 'Placed Bottle', ['Bottle'] = 'Placed Bottle or Alchemy Table', ['Placed Bottle'] = 'Placed Bottle or Alchemy Table', ['Alchemy Table'] = 'Placed Bottle or Alchemy Table', ['Water'] = 'Water or Sink', ['Sink'] = 'Water or Sink', ['Crystal Ball and Water'] = 'Crystal Ball and Water or Sink', ['Sky Mill and Water'] = 'Sky Mill and Water or Sink', ['Sky Mill and Snow Biome'] = 'Sky Mill and Snow Biome', ['Crystal Ball and Honey'] = 'Crystal Ball and Honey', ['Crystal Ball and Lava'] = 'Crystal Ball and Lava', },		-- for -- ['default_sep_compact'] = " or ", ['default_sep_ingredients'] = "or", ['compact_snow_biome'] = 'Snow', },	['de'] = { -- for -- ['cate_unexcepted_rows_count'] = 'Rezepte-Tabelle mit unerwarteter Gesamtzahl an Zeilen', ['cate_no_row'] = 'Rezepte-Tabelle ohne Zeilen', ['header_result'] = 'Resultat', ['header_ingredients'] = 'Zutaten', ['header_station'] = 'Herstellungsobjekt',

['cate_craftable'] = 'Herstellbare Gegenstände',

['station_by_hand'] = 'kein Objekt', ['station_sep_or'] = " oder ", ['station_sep_and'] = " und ",

['ingredients_sep'] = " oder ", ['snow_biome'] = 'Tundra',

['station_cate'] = { ['Lead Anvil'] = 'Eisen- oder Bleiamboss', ['Iron Anvil'] = 'Eisen- oder Bleiamboss', ['Orichalcum Anvil'] = 'Mithril- oder Oreichalkosamboss', ['Mythril Anvil'] = 'Mithril- oder Oreichalkosamboss', ['Demon Altar'] = 'Dämonen- oder Purpur-Altar', ['Crimson Altar'] = 'Dämonen- oder Purpur-Altar', ['Altar'] = 'Dämonen- oder Purpur-Altar', ['Titanium Forge'] = 'Adamantit- oder Titanschmiede', ['Adamantite Forge'] = 'Adamantit- oder Titanschmiede', ['Cauldron'] = 'Kochtopf oder Kessel', ['Cooking Pot'] = 'Kochtopf oder Kessel', ['Bottle only'] = 'Platzierte Flasche', ['Placed Bottle only'] = 'Platzierte Flasche', ['Bottle'] = 'Platzierte Flasche oder Alchemietisch', ['Placed Bottle'] = 'Platzierte Flasche oder Alchemietisch', ['Alchemy Table'] = 'Platzierte Flasche oder Alchemietisch', ['Water'] = 'Wasser oder Waschbecken', ['Sink'] = 'Wasser oder Waschbecken', ['Crystal Ball and Water'] = 'Kristallkugel und Wasser oder Waschbecken', ['Sky Mill and Snow Biome'] = 'Himmelsmühle und Tundra', ['Sky Mill and Water'] = 'Himmelsmühle und Wasser oder Waschbecken', ['Crystal Ball and Lava'] = 'Kristallkugel und Lava', ['Crystal Ball and Honey'] = 'Kristallkugel und Honig', },		-- for -- ['default_sep_compact'] = " oder ", ['default_sep_ingredients'] = "oder", ['compact_snow_biome'] = 'Tundra', },	['fr'] = { -- for -- ['cate_unexcepted_rows_count'] = 'Table des recettes avec un nombre de lignes total inattendu', ['cate_no_row'] = 'Table des recettes avec aucune ligne ligne', ['header_result'] = 'Résultat', ['header_ingredients'] = 'Ingrédients', ['header_station'] = 'Station d\'artisanat',

['cate_craftable'] = 'Objets façonnables',

['station_by_hand'] = 'À la main', ['station_sep_or'] = " ou ", ['station_sep_and'] = " et ",

['ingredients_sep'] = " ou ", ['snow_biome'] = 'Toundra',

['station_cate'] = { ['Lead Anvil'] = 'Enclume en fer ou en plomb', ['Iron Anvil'] = 'Enclume en fer ou en plomb', ['Orichalcum Anvil'] = 'Enclume en mithril ou en orichalque', ['Mythril Anvil'] = 'Enclume en mithril ou en orichalque', ['Demon Altar'] = 'Autel démoniaque ou carmin', ['Crimson Altar'] = 'Autel démoniaque ou carmin', ['Altar'] = 'Autel démoniaque ou carmin', ['Titanium Forge'] = 'Forge en adamantite ou en titane', ['Adamantite Forge'] = 'Forge en adamantite ou en titane', ['Cauldron'] = 'Marmite ou Chaudron', ['Cooking Pot'] = 'Marmite ou Chaudron', ['Bottle only'] = 'Bouteille placée', ['Placed Bottle only'] = 'Bouteille placée', ['Bottle'] = 'Bouteille placée ou Table d\'alchimie', ['Placed Bottle'] = 'Bouteille placée ou Table d\'alchimie', ['Alchemy Table'] = 'Bouteille placée ou Table d\'alchimie', ['Water'] = 'Eau ou Évier', ['Sink'] = 'Eau ou Évier', ['Crystal Ball and Water'] = 'Boule de cristal et Eau ou Évier', ['Sky Mill and Water'] = 'Moulin céleste et Eau ou Évier', ['Sky Mill and Snow Biome'] = 'Moulin céleste et Toundra', ['Crystal Ball and Honey'] = 'Boule de cristal et Miel', ['Crystal Ball and Lava'] = 'Boule de cristal et Lave', },		-- for -- ['default_sep_compact'] = " ou ", ['default_sep_ingredients'] = "ou", ['compact_snow_biome'] = 'Toundra', },	['lt'] = { -- for -- ['cate_unexcepted_rows_count'] = 'Recipes table with unexcepted total number of rows', ['cate_no_row'] = 'Recipes table with no row', ['header_result'] = 'Rezultatas', ['header_ingredients'] = 'Medžiaga(-os)', ['header_station'] = 'Gaminimo vieta',

['cate_craftable'] = 'Craftable items/lt',

['station_by_hand'] = 'By Hand', ['station_sep_or'] = " or ", ['station_sep_and'] = " and ",

['ingredients_sep'] = " or ", ['snow_biome'] = 'Snow biome',

['station_cate'] = { ['Lead Anvil'] = 'Iron or Lead Anvil', ['Iron Anvil'] = 'Iron or Lead Anvil', ['Orichalcum Anvil'] = 'Mythril or Orichalcum Anvil', ['Mythril Anvil'] = 'Mythril or Orichalcum Anvil', ['Demon Altar'] = 'Demon or Crimson Altar', ['Crimson Altar'] = 'Demon or Crimson Altar', ['Altar'] = 'Demon or Crimson Altar', ['Titanium Forge'] = 'Adamantite or Titanium Forge', ['Adamantite Forge'] = 'Adamantite or Titanium Forge', ['Cauldron'] = 'Cooking Pot or Cauldron', ['Cooking Pot'] = 'Cooking Pot or Cauldron', ['Bottle only'] = 'Placed Bottle', ['Placed Bottle only'] = 'Placed Bottle', ['Bottle'] = 'Placed Bottle or Alchemy Table', ['Placed Bottle'] = 'Placed Bottle or Alchemy Table', ['Alchemy Table'] = 'Placed Bottle or Alchemy Table', ['Water'] = 'Water or Sink', ['Sink'] = 'Water or Sink', ['Crystal Ball and Water'] = 'Crystal Ball and Water or Sink', ['Sky Mill and Water'] = 'Sky Mill and Water or Sink', ['Sky Mill and Snow Biome'] = 'Sky Mill and Snow Biome', ['Crystal Ball and Honey'] = 'Crystal Ball and Honey', ['Crystal Ball and Lava'] = 'Crystal Ball and Lava', },		-- for -- ['default_sep_compact'] = " or ", ['default_sep_ingredients'] = "or", ['compact_snow_biome'] = 'Snow', },	['pl'] = { -- for -- ['cate_unexcepted_rows_count'] = 'Recipes table with unexcepted total number of rows', ['cate_no_row'] = 'Recipes table with no row', ['header_result'] = 'Wynik', ['header_ingredients'] = 'Składniki', ['header_station'] = 'Stacja rzemieślnicza',

['cate_craftable'] = 'Rzeczy do stworzenia',

['station_by_hand'] = 'Dłoń', ['station_sep_or'] = " albo ", ['station_sep_and'] = " oraz ",

['ingredients_sep'] = " lub ", ['snow_biome'] = 'Biom śnieżny',

['station_cate'] = { ['Lead Anvil'] = 'Żelazne albo Ołowiane kowadło', ['Iron Anvil'] = 'Żelazne albo Ołowiane kowadło', ['Orichalcum Anvil'] = 'Mythril or Orichalcum Anvil', ['Mythril Anvil'] = 'Mythril or Orichalcum Anvil', ['Demon Altar'] = 'Demoniczny albo Szkarłatny ołtarz', ['Crimson Altar'] = 'Demoniczny albo Szkarłatny ołtarz', ['Altar'] = 'Demoniczny albo Szkarłatny ołtarz', ['Titanium Forge'] = 'Adamantite or Titanium Forge', ['Adamantite Forge'] = 'Adamantite or Titanium Forge', ['Cauldron'] = 'Cooking Pot or Cauldron', ['Cooking Pot'] = 'Cooking Pot or Cauldron', ['Bottle only'] = 'Położona butelka', ['Placed Bottle only'] = 'Położona butelka', ['Bottle'] = 'Placed Bottle or Alchemy Table', ['Placed Bottle'] = 'Położona butelka albo Alchemy Table', ['Alchemy Table'] = 'Położona butelka albo Alchemy Table', ['Water'] = 'Woda albo Umywalka', ['Sink'] = 'Woda albo Umywalka', ['Crystal Ball and Water'] = 'Crystal Ball and Water or Sink', ['Sky Mill and Water'] = 'Sky Mill and Water or Sink', ['Sky Mill and Snow Biome'] = 'Sky Mill and Snow Biome', ['Crystal Ball and Honey'] = 'Crystal Ball and Honey', ['Crystal Ball and Lava'] = 'Crystal Ball and Lava', },		-- for -- ['default_sep_compact'] = " albo ", ['default_sep_ingredients'] = "albo", ['compact_snow_biome'] = 'Śnieg', },	['zh'] = { -- for -- ['cate_unexcepted_rows_count'] = 'Recipes table with unexcepted total number of rows', ['cate_no_row'] = 'Recipes table with no row', ['header_result'] = '产物', ['header_ingredients'] = '材料', ['header_station'] = '制作站',

['cate_craftable'] = '可制作物品',

['station_by_hand'] = '徒手', ['station_sep_or'] = " 或 ", ['station_sep_and'] = " 和 ",

['ingredients_sep'] = " 或 ", ['snow_biome'] = '雪原生物群落',

['station_cate'] = { ['Lead Anvil'] = '铁砧或铅砧', ['Iron Anvil'] = '铁砧或铅砧', ['Orichalcum Anvil'] = '秘银砧或山铜砧', ['Mythril Anvil'] = '秘银砧或山铜砧', ['Demon Altar'] = '恶魔祭坛或猩红祭坛', ['Crimson Altar'] = '恶魔祭坛或猩红祭坛', ['Altar'] = '恶魔祭坛或猩红祭坛', ['Titanium Forge'] = '精金熔炉或钛金熔炉', ['Adamantite Forge'] = '精金熔炉或钛金熔炉', ['Cauldron'] = '烹饪锅或大锅', ['Cooking Pot'] = '烹饪锅或大锅', ['Bottle only'] = '放置的瓶子', ['Placed Bottle only'] = '放置的瓶子', ['Bottle'] = '放置的瓶子或炼药桌', ['Placed Bottle'] = '放置的瓶子或炼药桌', ['Alchemy Table'] = '放置的瓶子或炼药桌', ['Water'] = '水或水槽', ['Sink'] = '水或水槽', ['Crystal Ball and Water'] = '水晶球和水或水槽', ['Sky Mill and Water'] = '天磨和水或水槽', ['Sky Mill and Snow Biome'] = '天磨和雪原生物群落', ['Crystal Ball and Honey'] = '水晶球和蜂蜜', ['Crystal Ball and Lava'] = '水晶球和熔岩', },		-- for -- ['default_sep_compact'] = " 或 ", ['default_sep_ingredients'] = "或", ['compact_snow_biome'] = '雪原', }, }

local l10n_auto_translate_eicons_pagename = { ['zh'] = true, }

--- The following is not related to l10n. --

local item_link = require('Module:Item').go local trim = mw.text.trim local cargo = mw.ext.cargo

local currentFrame -- global cache for current frame object. local inputArgs -- global args cache. local lang -- cache current lang. local l10n_table

local l10n = function(key) return l10n_table[key] or l10n_info['en'][key] end

local extCols_stationBefore = nil local extCols_stationAfter = nil

local extCols_A = nil local extCols_B = nil local extCols_C = nil local extCols_D = nil

function getArg(key) local v = trim(inputArgs[key] or '') if v=='' then return nil else return v	end end

local itemLink = function(name, args) local args = args or {} args[1] = name args[2] = currentFrame:expandTemplate{ title = 'tr', args = {name, lang=lang} } args['eicons'] = l10n_auto_translate_eicons_pagename[lang] args['small'] = 'y'	args['lang'] = lang or 'en' args['nolink'] = args['nolink'] and 'y' or nil return item_link(currentFrame, args) end

-- credit: http://richard.warburton.it -- this version is with trim. local explode = function(div,str) if (div=='') then return false end local pos,arr = 0,{} -- for each divider found for st,sp in function return string.find(str,div,pos,true) end do		table.insert(arr, trim(string.sub(str,pos,st-1))) -- Attach chars left of current divider pos = sp + 1 -- Jump past current divider end table.insert(arr, trim(string.sub(str,pos))) -- Attach chars right of last divider return arr end

-- return an array of itemname, split xxx/yyy to item1=xxx, item2=yyy. If it's something like "Lead/Iron Bar", it will normalize as item1 = Iron Bar, item2 = Lead Bar. local split = (function	local metals = {		['Copper/Tin'] = 1,		['Silver/Tungsten'] = 1,		['Gold/Platinum'] = 1,		['Iron/Lead'] = 1,		['Cobalt/Palladium'] = 1,		['Mythril/Orichalcum'] = 1,		['Adamantite/Titanium'] = 1,		['Tin/Copper'] = 2,		['Tungsten/Silver'] = 2,		['Platinum/Gold'] = 2,		['Lead/Iron'] = 2,		['Palladium/Cobalt'] = 2,		['Orichalcum/Mythril'] = 2,		['Titanium/Adamantite'] = 2,	}	return function(name)		local count = select(2, name:gsub("/", "/", 2))		if count == 0 then			-- only 1 item			return { trim(name) }		elseif count == 1 then			-- 2 items			local item1a, item1b, item2a, item2b = name:match("^%s*(%S+)%s*(.-)/%s*(%S+)%s*(.-)$")			local x = metals[item1a..'/'..item2a]			if tostring(item1b) == '' and x then				item1b = item2b			end			if x == 2 then				return {trim(item2a..' '..item2b), trim(item1a..' '..item1b)}			else				return {trim(item1a..' '..item1b), trim(item2a..' '..item2b)} end else -- 3 or more items return explode('/', name) end end end)

-- return 1 or 2 value(s), when input is name[note], return item, note. local itemname = function(str) local item, note = str:match("^(.-)(%b[])$") if item then return item, note else return str end end

-- normalize ingredient name input, Lead Bar=>¦Lead Bar¦, Iron/Lead Bar => ¦Iron Bar¦Lead Bar¦, Lead/Iron Bar => ¦Iron Bar¦Lead Bar¦ .... local normalize = function(name) local result = '¦' for k, v in ipairs(split(name)) do result = result .. itemname(v) .. '¦'	end return result end

local escape = function(str) return str:gsub("'", "\\'"):gsub("&#39;", "\\'") end local enclose = function(str) return "'" .. escape(str) .. "'" end

local getItemGroupName = function(item) if item == 'Wood' or item == 'Ebonwood' or item == 'Rich Mahogany' or item == 'Pearlwood' or item == 'Shadewood' or item == 'Spooky Wood' or item == 'Boreal Wood' or item == 'Palm Wood' then return 'Any Wood' elseif item == 'Iron Bar' or item == 'Lead Bar' then return 'Any Iron Bar' elseif item == 'Sand Block' or item == 'Pearlsand Block' or item == 'Crimsand Block' or item == 'Ebonsand Block' or item == 'Hardened Sand Block' then return 'Any Sand' elseif item == 'Red Pressure Plate' or item == 'Green Pressure Plate' or item == 'Gray Pressure Plate' or item == 'Brown Pressure Plate' or item == 'Blue Pressure Plate' or item == 'Yellow Pressure Plate' or item == 'Lihzahrd Pressure Plate' then return 'Any Pressure Plate' elseif item == 'Bird' or item == 'Blue Jay' or item == 'Cardinal' then return 'Any Bird' elseif item == 'Black Scorpion' or item == 'Scorpion' then return 'Any Scorpion' elseif item == 'Squirrel' or item == 'Red Squirrel' then return 'Any Squirrel' elseif item == 'Grubby' or item == 'Sluggy' or item == 'Buggy' then return 'Any Bug' elseif item == 'Mallard Duck' or item == 'Duck' then return 'Any Duck' elseif item == 'Sulphur Butterfly' or item == 'Julia Butterfly' or item == 'Monarch Butterfly' or item == 'Purple Emperor Butterfly' or item == 'Red Admiral Butterfly' or item == 'Tree Nymph Butterfly' or item == 'Ulysses Butterfly' or item == 'Zebra Swallowtail Butterfly' then return 'Any Butterfly' elseif item == 'Firefly' or item == 'Lightning Bug' then return 'Any Firefly' elseif item == 'Snail' or item == 'Glowing Snail' then return 'Any Snail' end end

local normalizeStation = function(station) if station == 'Altar' then station = 'Demon Altar' end return station end

local normalizeVersion = function(_version) local _version = trim(_version):lower local version = '' if _version:find('desktop', 1, true) then version = version .. ' desktop' end if _version:find('console', 1, true) then version = version .. ' console' end if _version:find('old-gen', 1, true) then version = version .. ' old-gen' end if _version:find('japan', 1, true) then version = version .. ' japan' end if _version:find('mobile', 1, true) then version = version .. ' mobile' end if _version:find('3ds', 1, true) then version = version .. ' 3ds' end if version == ' desktop console old-gen mobile 3ds' then version = '' end return trim(version) end

local criStr = function(args) local constraints = {} -- station = ? and station != ? local _station = trim(args['station'] or '') local _stationnot = trim(args['stationnot'] or '') local str = '' if _station ~= '' then for _, v in ipairs(explode('/', _station)) do			if str ~= '' then str = str .. ' OR ' end str = str .. "station = " .. enclose(normalizeStation(v)) end end if _stationnot ~= '' then if str ~= '' then str = '(' .. str .. ')' end for _, v in ipairs(explode('/', _stationnot)) do			if str ~= '' then str = str .. ' AND ' end str = str .. 'station <> ' .. enclose(normalizeStation(v)) end end constraints['station'] = str -- result = ? and result != ? local _result = trim(args['result'] or '') local _resultnot = trim(args['resultnot'] or '') local str = '' if _result ~= '' then for _, v in ipairs(explode('/', _result)) do			if str ~= '' then str = str .. ' OR ' end if mw.ustring.sub(v, 1, 5) == 'LIKE ' then str = str .. "result LIKE " .. enclose(trim(mw.ustring.sub(v, 6))) else str = str .. 'result=' .. enclose(v) end end end if _resultnot ~= '' then if str ~= '' then str = '(' .. str .. ')' end for _, v in ipairs(explode('/', _resultnot)) do			if str ~= '' then str = str .. ' AND ' end if mw.ustring.sub(v, 1, 5) == 'LIKE ' then str = str .. "result NOT LIKE " .. enclose(trim(mw.ustring.sub(v, 6))) else str = str .. 'result <> ' .. enclose(v) end end end if str ~= '' then constraints['result'] = str end -- ingredient = ? local _ingredient = trim(args['ingredient'] or '') if _ingredient ~= '' then local str = '' for _, v in ipairs(explode('/', _ingredient)) do			if str ~= '' then str = str .. ' OR ' end if mw.ustring.sub(v, 1, 1) == '#' then str = str .. "ingredients HOLDS LIKE '%¦" .. escape(mw.ustring.sub(v, 2)) .. "¦%'"			elseif mw.ustring.sub(v, 1, 5) == 'LIKE ' then str = str .. "ingredients HOLDS LIKE '%¦" .. escape(trim(mw.ustring.sub(v, 6))) .. "¦%'"			else str = str .. "ingredients HOLDS LIKE '%¦" .. escape(v) .. "¦%'"				-- any xxx local group = getItemGroupName(v) if group then str = str .. " OR ingredients HOLDS LIKE '%¦" .. escape(group) .. "¦%'"				end end end constraints['ingredient'] = str end

--versions local _version = normalizeVersion(args['version'] or args['versions'] or '') if _version ~= '' then constraints['version'] = 'version = '..enclose(_version) .. ' OR version IS NULL' end

local where = '' if constraints['station'] then where = constraints['station'] end if constraints['result'] then if where ~= '' then where = where .. ' AND ' end where = where .. '(' .. constraints['result'] .. ')' end if constraints['ingredient'] then if where ~= '' then where = where .. ' AND ' end where = where .. '(' .. constraints['ingredient'] .. ')' end if constraints['version'] then if where ~= '' then where = where .. ' AND ' end where = where .. '(' .. constraints['version'] .. ')' end return where end

local resultCellIngredientSum = function(row, rowKey, rowVersion, showResultId, needLink, noVersion, template) local result, resultid, resultimage, resulttext, amount, version = rowKey, row['_resultid'], row['_resultimage'], row['_resulttext'], row['_amount'], rowVersion local str = '' local args = {anchor = 'y', nolink = not needLink, class='multi-line'} if showResultId then args['id'] = resultid end if resultimage then args['image'] = resultimage end if resulttext then args[2] = resulttext end str = str .. itemLink(result, args) if amount ~= '1' then str = str .. ' ('..amount..') ' end if not noVersion then if version ~= '' then str = str .. ' (' ..currentFrame:expandTemplate{ title = 'version icons', args = {version} }..')' end end if template then local template_str = currentFrame:expandTemplate{ title = template, args = { link = needLink, showid = showResultId, noversion = noVersion, resultid=resultid, resultimage=resultimage, resulttext=resulttext, result=result, amount=amount, versions=version, } }		str = template_str:gsub('@@@@', str) else str = '' .. str .. '' end return str end

local resultCell = function(row, showResultId, needLink, noVersion, template) local result, resultid, resultimage, resulttext, amount, version = row['result'], row['resultid'], row['resultimage'], row['resulttext'], row['amount'], row['version'] local str = '' local args = {anchor = 'y', nolink = not needLink, class='multi-line'} if showResultId then args['id'] = resultid end if resultimage then args['image'] = resultimage end if resulttext then args[2] = resulttext end if version ~= '' then args['icons'] = 'n'	end str = str .. itemLink(result, args) if amount ~= '1' then str = str .. ' ('..amount..') ' end if not noVersion then if version ~= '' then str = str .. ' (' ..currentFrame:expandTemplate{ title = 'version icons', args = {version} }..')' end end if template then local template_str = currentFrame:expandTemplate{ title = template, args = { link = needLink, showid = showResultId, noversion = noVersion, resultid=resultid, resultimage=resultimage, resulttext=resulttext, result=result, amount=amount, versions=version, } }		str = template_str:gsub('@@@@', str) end return str end

local ingredientsCell = function(args) local str = '' for _, v in ipairs(explode('^', args)) do str = str .. '' local item, amount = v:match('^(.-)¦(.-)$') local s		for _, itemname in ipairs(split(item)) do			if s then s = s .. l10n('ingredients_sep') .. itemLink(itemname) else s = itemLink(itemname) end end str = str .. s		if amount ~= '1' then str = str .. ' ('..amount..') ' end str = str .. '' end str = str .. '' return str end

local ingredientsCellIngredientSum = function(ingSum, ingSumKeys) local str = '' for i, k in ipairs(ingSumKeys) do		local item = k		local amount = ingSum[k] str = str .. '' local s		for _, itemname in ipairs(split(item)) do			if s then s = s .. l10n('ingredients_sep') .. itemLink(itemname) else s = itemLink(itemname) end end str = str .. s		if amount ~= '1' then str = str .. ' (' .. amount .. ') ' end str = str .. '' end str = str .. '' return str end

local stationCell = function(station, options, compact) options = options or {wrap = 'y'} local station_sep_or = l10n('station_sep_or') local station_sep_and = l10n('station_sep_and') if compact then station_sep_or = l10n('station_sep_or_compact') station_sep_and = l10n('station_sep_and') end if station == 'By Hand' then return l10n('station_by_hand') elseif station == 'Furnace' or station == 'Work Bench' or station == 'Sawmill' or station == "Tinkerer's Workshop" or station == 'Dye Vat' or station == 'Loom' or station == 'Keg' or station == 'Hellforge' or station == 'Bookcase' or station == 'Imbuing Station' or station == 'Lava' or station == 'Honey' or station == 'Glass Kiln' or station == 'Flesh Cloning Vat' or station == 'Autohammer' or station == 'Crystal Ball' or station == 'Ice Machine' or station == 'Meat Grinder' or station == 'Living Loom' or station == 'Heavy Work Bench' or station == 'Sky Mill' or station == 'Solidifier' or station == 'Honey Dispenser' or station == 'Bone Welder' or station == 'Blend-O-Matic' or station == 'Steampunk Boiler' or station == 'Ancient Manipulator' or station == 'Lihzahrd Furnace' or station == 'Living Wood' then return itemLink(station, options) elseif station == 'Iron Anvil' then return itemLink('Iron Anvil', options) .. station_sep_or .. itemLink('Lead Anvil', options) elseif station == 'Adamantite Forge' then return itemLink('Adamantite Forge', options) .. station_sep_or .. itemLink('Titanium Forge', options) elseif station == 'Mythril Anvil' then return itemLink('Mythril Anvil', options) .. station_sep_or .. itemLink('Orichalcum Anvil', options) elseif station == 'Demon Altar' then return itemLink('Demon Altar', options) .. station_sep_or .. itemLink('Crimson Altar', options) elseif station == 'Cooking Pot' then return itemLink('Cooking Pot', options) .. station_sep_or .. itemLink('Cauldron', options) elseif station == 'Placed Bottle' then return itemLink('Placed Bottle', options) .. station_sep_or .. itemLink('Alchemy Table', options) elseif station == 'Water' then return itemLink('Water', options) .. station_sep_or .. itemLink('Sink', options) elseif station == 'Table and Chair' then return itemLink('Table', options) .. station_sep_and .. itemLink('Chair', options) elseif station == 'Work Bench and Chair' then return itemLink('Work Bench', options) .. station_sep_and .. itemLink('Chair', options) elseif station == 'Crystal Ball and Lava' then return itemLink('Crystal Ball', options) .. station_sep_and .. itemLink('Lava', options) elseif station == 'Crystal Ball and Honey' then return itemLink('Crystal Ball', options) .. station_sep_and .. itemLink('Honey', options) elseif station == 'Crystal Ball and Water' then return itemLink('Crystal Ball', options) .. station_sep_and.. ' ' .. itemLink('Water', options) .. station_sep_or .. itemLink('Sink', options) .. ' '	elseif station == 'Sky Mill and Water' then return itemLink('Sky Mill', options) .. station_sep_and.. ' ' .. itemLink('Water', options) .. station_sep_or .. itemLink('Sink', options) .. ' '	elseif station == 'Sky Mill and Snow Biome' then return itemLink('Sky Mill', options) .. station_sep_and.. l10n('snow_biome') elseif station == 'Placed Bottle only' then return itemLink('Placed Bottle', options) else return station end end

-- for extract and ingredientsum. local compactStation = function(station, sep) sep = sep or ' @&thinsp;' -- default sep if station == 'By Hand' then return '' elseif station == 'Furnace' or station == 'Work Bench' or station == 'Sawmill' or station == "Tinkerer's Workshop" or station == 'Dye Vat' or station == 'Loom' or station == 'Keg' or station == 'Hellforge' or station == 'Bookcase' or station == 'Imbuing Station' or station == 'Lava' or station == 'Honey' or station == 'Glass Kiln' or station == 'Flesh Cloning Vat' or station == 'Autohammer' or station == 'Crystal Ball' or station == 'Ice Machine' or station == 'Meat Grinder' or station == 'Living Loom' or station == 'Heavy Work Bench' or station == 'Sky Mill' or station == 'Solidifier' or station == 'Honey Dispenser' or station == 'Bone Welder' or station == 'Blend-O-Matic' or station == 'Steampunk Boiler' or station == 'Ancient Manipulator' or station == 'Lihzahrd Furnace' or station == 'Living Wood' then return sep .. itemLink(station, {mode = 'image'}) elseif station == 'Iron Anvil' then return sep .. itemLink('Iron Anvil', {mode = 'image'}) .. "&thinsp;/&thinsp;" .. itemLink('Lead Anvil', {mode = 'image'}) elseif station == 'Adamantite Forge' then return sep .. itemLink('Adamantite Forge', {mode = 'image'}) .. "&thinsp;/&thinsp;" .. itemLink('Titanium Forge', {mode = 'image'}) elseif station == 'Mythril Anvil' then return sep .. itemLink('Mythril Anvil', {mode = 'image'}) .. "&thinsp;/&thinsp;" .. itemLink('Orichalcum Anvil', {mode = 'image'}) elseif station == 'Demon Altar' then return sep .. itemLink('Demon Altar', {mode = 'image'}) .. "&thinsp;/&thinsp;" .. itemLink('Crimson Altar', {mode = 'image'}) elseif station == 'Cooking Pot' then return sep .. itemLink('Cooking Pot', {mode = 'image'}) .. "&thinsp;/&thinsp;" .. itemLink('Cauldron', {mode = 'image'}) elseif station == 'Placed Bottle' then return sep .. itemLink('Placed Bottle', {mode = 'image'}) .. "&thinsp;/&thinsp;" .. itemLink('Alchemy Table', {mode = 'image'}) elseif station == 'Water' then return sep .. itemLink('Water', {mode = 'image'}) .. "&thinsp;/&thinsp;" .. itemLink('Sink', {mode = 'image'}) elseif station == 'Table and Chair' then return sep .. itemLink('Table', {mode = 'image'}) .. "&thinsp;&amp;&thinsp;" .. itemLink('Chair', {mode = 'image'}) elseif station == 'Work Bench and Chair' then return sep .. itemLink('Work Bench', {mode = 'image'}) .. "&thinsp;&amp;&thinsp;" .. itemLink('Chair', {mode = 'image'}) elseif station == 'Crystal Ball and Lava' then return sep .. itemLink('Crystal Ball', {mode = 'image'}) .. "&thinsp;&amp;&thinsp;" .. itemLink('Lava', {mode = 'image'}) elseif station == 'Crystal Ball and Honey' then return sep .. itemLink('Crystal Ball', {mode = 'image'}) .. "&thinsp;&amp;&thinsp;" .. itemLink('Honey', {mode = 'image'}) elseif station == 'Crystal Ball and Water' then return sep .. itemLink('Crystal Ball', {mode = 'image'}) .. "&thinsp;&amp;&thinsp;".. '(&thinsp;' .. itemLink('Water', {mode = 'image'}) .. "&thinsp;/&thinsp;" .. itemLink('Sink', {mode = 'image'}) .. '&thinsp;)' elseif station == 'Sky Mill and Water' then return sep .. itemLink('Sky Mill', {mode = 'image'}) .. "&thinsp;&amp;&thinsp;".. '(&thinsp;' .. itemLink('Water', {mode = 'image'}) .. "&thinsp;/&thinsp;" .. itemLink('Sink', {mode = 'image'}) .. '&thinsp;)' elseif station == 'Sky Mill and Snow Biome' then return sep .. itemLink('Sky Mill', {mode = 'image'}) .. "&thinsp;&amp;&thinsp;".. l10n('compact_snow_biome') elseif station == 'Placed Bottle only' then return sep .. itemLink('Placed Bottle', {mode = 'image'}) else return sep .. station end end

local getFlags = function(args) local needCate = 1 local needLink = true local _cate = trim(args['cate'] or '') if _cate == 'force' or _cate == 'all' then needCate = 2 elseif _cate == 'n' or _cate == 'no' then needCate = nil end local _link = trim(args['link'] or '') if _link == 'y' or _link == 'yes' or _link == 'force' then needLink = true elseif _link == 'n' or _link == 'no' then needLink = false end return needCate, needLink end

local identicalTables = function(a, b)	if table.maxn(a) ~= table.maxn(b) then return false else local i = 0 for _, v in pairs(a) do			for _, w in pairs(b) do				if v == w then i = i+1 end end end return i == table.maxn(a) end end

local subset = function(a, b) -- is table 'a' a subset of table 'b'? if table.maxn(a) > table.maxn(b) then return false else local i = 0 for _, v in pairs(a) do			for _, w in pairs(b) do				if v == w then i = i+1 end end end return i == table.maxn(a) end end

local removeEmptyElements = function(t, mode) if mode == 1 then -- table of strings local continue = true -- keep iterating over the table until no more empty elements are found while(continue) do			if next(t) == nil then continue = false end for i, v in pairs(t) do				if v == nil or v == '' then table.remove(t, i)					continue = true break else continue = false end end end return t	else -- table of tables local continue = true -- keep iterating over the table until no more empty elements are found while(continue) do			if next(t) == nil then continue = false end for i, v in pairs(t) do				if next(v) == nil then table.remove(t, i)					continue = true break else continue = false end end end return t	end end

local tablelength = function(t) local count = 0 for _ in pairs(t) do count = count + 1 end return count end

local getIngSum = function(row) local ingSum = {} for k, v in pairs(row.ingredients) do		for item, amount in pairs(v) do			if string.sub(item, 1, 1) ~= '_' then -- informations about result; not actual ingredients if ingSum[item] then ingSum[item] = ingSum[item] + amount else ingSum[item] = amount end end end end return ingSum end

local getIngSumKeys = function(ingSum) -- sort ings local ingSumKeys = {} for k in pairs(ingSum) do		table.insert(ingSumKeys, k)	end table.sort(ingSumKeys) return ingSumKeys end

local addCate, cateStr -- for table body. init in p.query

local tableStart = function(title, withStation) local header_ local str = ' total: '..rows_count..' row(s)   ' if expectedrows and rows_count ~= expectedrows then str = str .. ''	end if not expectedrows and rows_count == 0 then str = str .. ''	end return str end

local tableRow = function(str, row, current_station, station_count, rows_count, showResultId, withStation, needCate, needLink, needGroup, current_result, result_count, current_result_ext, result_ext_count, template) local str_w = '' -- before result col local str_x = '' -- between result and ingredients cols local str_y = '' -- between ingredients and station cols local str_z = '' -- after station local str_resultCell = ''

local result_index = getArg('result-index-#'..rows_count) or getArg('result-index-'..row['result']..'-'..row['version']) or getArg('result-index-'..row['result'])

str = str .. ''

if needGroup then local result = row['result']..'|'..row['resultid']..'|'..row['resultimage']..'|'..row['resulttext']..'|'..row['amount']..'|'..row['version'] -- grouping result col if current_result == result then -- is same group ?? result_count = result_count + 1 else --new group: -- rowspan value for prev group, if needed. if result_count then str = str:gsub("yyyrowspanyyy", tostring(result_count)) end -- begin this group current_result = result result_count = 1 str_resultCell = ''.. resultCell(row, showResultId, needLink, false, template).. ' '		end -- grouping ext cols if result_index and (current_result_ext == result_index) then -- is same group ?? result_ext_count = result_ext_count + 1 else --new group: -- rowspan value for prev group, if needed. if result_ext_count then str = str:gsub("zzzrowspanzzz", tostring(result_ext_count)) end -- begin this group current_result_ext = result_index result_ext_count = 1 if extCols_A then for _, v in ipairs(extCols_A) do					if result_index then str_w = str_w .. '' .. (getArg(result_index .. '-row-' .. v) or '') .. ' '					else str_w = str_w .. ' ' end end end if extCols_B then for _, v in ipairs(extCols_B) do					if result_index then str_x = str_x .. '' .. (getArg(result_index .. '-row-' .. v) or '') .. ' '					else str_x = str_x .. '<td class="'..v..'" rowspan="zzzrowspanzzz"> ' end end end if extCols_C then for _, v in ipairs(extCols_C) do					if result_index then str_y = str_y .. '<td class="'..v..'" rowspan="zzzrowspanzzz">' .. (getArg(result_index .. '-row-' .. v) or '') .. ' '					else str_y = str_y .. '<td class="'..v..'" rowspan="zzzrowspanzzz"> ' end end end if extCols_D then for _, v in ipairs(extCols_D) do					if result_index then str_z = str_z .. '<td class="'..v..'" rowspan="zzzrowspanzzz">' .. (getArg(result_index .. '-row-' .. v) or '') .. ' '					else str_z = str_z .. '<td class="'..v..'" rowspan="zzzrowspanzzz"> ' end end end end else if extCols_A then for _, v in ipairs(extCols_A) do				if result_index then str_w = str_w .. '<td class="'..v..'">' .. (getArg(result_index .. '-row-' .. v) or '') .. ' '				else str_w = str_w .. '<td class="'..v..'"> ' end end end if extCols_B then for _, v in ipairs(extCols_B) do				if result_index then str_x = str_x .. '<td class="'..v..'">' .. (getArg(result_index .. '-row-' .. v) or '') .. ' '				else str_x = str_x .. '<td class="'..v..'"> ' end end end if extCols_C then for _, v in ipairs(extCols_C) do				if result_index then str_y = str_y .. '<td class="'..v..'">' .. (getArg(result_index .. '-row-' .. v) or '') .. ' '				else str_y = str_y .. '<td class="'..v..'"> ' end end end if extCols_D then for _, v in ipairs(extCols_D) do				if result_index then str_z = str_z .. '<td class="'..v..'">' .. (getArg(result_index .. '-row-' .. v) or '') .. ' '				else str_z = str_z .. '<td class="'..v..'"> ' end end end str_resultCell = ' '.. resultCell(row, showResultId, needLink, false, template).. ' '	end

str = str .. str_w .. str_resultCell .. str_x .. ' ' .. ingredientsCell(row['args']).. ' ' .. str_y

if withStation then local station = row['station'] if current_station == station then -- is same group ?? station_count = station_count + 1 else --new group: -- rowspan value for prev group, if needed. if station_count then str = str:gsub("xxxrowspanxxx", tostring(station_count)) end -- begin this group current_station = station station_count = 1 local station_index = getArg('station-index-'..station) -- station before: if extCols_stationBefore then for _, v in ipairs(extCols_stationBefore) do					if station_index then str = str .. '<td class="station '..v..'" rowspan="xxxrowspanxxx">' .. (getArg(station_index .. '-row-' .. v) or '') .. ' '					else str = str .. '<td class="station '..v..'" rowspan="xxxrowspanxxx"> ' end end end str = str .. '<td class="station" rowspan="xxxrowspanxxx">'.. stationCell(station) ..' ' -- station after: if extCols_stationAfter then for _, v in ipairs(extCols_stationAfter) do					if station_index then str = str .. '<td class="station '..v..'" rowspan="xxxrowspanxxx">' .. (getArg(station_index .. '-row-' .. v) or '') .. ' '					else str = str .. '<td class="station '..v..'" rowspan="xxxrowspanxxx"> ' end end end end end

str = str .. str_z ..' ' return str, current_station, station_count, current_result, result_count, current_result_ext, result_ext_count end

local extRows = function(withStation, isTop) local prefix if isTop then prefix = 'topextrow-' else prefix = 'extrow-' end local returnstr = '' local valid = true local p	local str local _i = 1 local temp while valid do local i = tostring(_i) .. '-'		p = prefix .. i		valid = false str = '<tr data-'..prefix..'id="'..tostring(_i)..'">' if extCols_A then for _, v in ipairs(extCols_A) do				temp = getArg(p..v)				if temp then valid = true str = str .. '<td class="'..v..'">' .. temp .. ' '				else str = str .. '<td class="'..v..'"> ' end end end temp = getArg(p..'col-result') if temp then valid = true str = str .. ' ' .. temp .. ' '		else str = str .. ' '		end if extCols_B then for _, v in ipairs(extCols_B) do				temp = getArg(p..v)				if temp then valid = true str = str .. '<td class="'..v..'">' .. temp .. ' '				else str = str .. '<td class="'..v..'"> ' end end end temp = getArg(p..'col-ingredients') if temp then valid = true str = str .. ' ' .. temp .. ' '		else str = str .. ' '		end if extCols_C then for _, v in ipairs(extCols_C) do				temp = getArg(p..v)				if temp then valid = true str = str .. '<td class="'..v..'">' .. temp .. ' '				else str = str .. '<td class="'..v..'"> ' end end end if withStation then -- station before: if extCols_stationBefore then for _, v in ipairs(extCols_stationBefore) do					temp = getArg(p..v)					if temp then valid = true str = str .. '<td class="station '..v..'">' .. temp .. ' '					else str = str .. '<td class="station '..v..'"> ' end end end temp = getArg(p..'col-station') if temp then valid = true str = str .. ' ' .. temp .. ' '			else str = str .. ' '			end -- station after: if extCols_stationAfter then for _, v in ipairs(extCols_stationAfter) do					temp = getArg(p..v)					if temp then valid = true str = str .. '<td class="station '..v..'">' .. temp .. ' '					else str = str .. '<td class="station '..v..'"> ' end end end end if extCols_D then for _, v in ipairs(extCols_D) do				temp = getArg(p..v)				if temp then valid = true str = str .. '<td class="'..v..'">' .. temp .. ' '				else str = str .. '<td class="'..v..'"> ' end end end str = str .. ' '

if valid then _i = _i + 1 returnstr = returnstr .. str end end return returnstr end

local tableBody = function(result, showResultId, withStation, needGroup, needCate, needLink, rootpagename, title, expectedrows, template) local str = tableStart(title, withStation) -- top ext rows: str = str .. extRows(withStation, true) -- main rows: local current_station local station_count local rows_count = 0 local current_result local result_count local current_result_ext local result_ext_count for _, row in ipairs(result) do			rows_count = rows_count + 1 -- table row: str, current_station, station_count, current_result, result_count, current_result_ext, result_ext_count = tableRow(str, row, current_station, station_count, rows_count, showResultId, withStation, needCate, needLink, needGroup, current_result, result_count, current_result_ext, result_ext_count, template) -- cate: if needCate then if needCate == 2 or rootpagename == currentFrame:expandTemplate{ title = 'tr', args = {row['result'], lang=lang} } then addCate(row['station']) end end end -- rowspan value for last station group and result group if station_count then str = str:gsub("xxxrowspanxxx", tostring(station_count)) end if needGroup then str = str:gsub("yyyrowspanyyy", tostring(result_count)) str = str:gsub("zzzrowspanzzz", tostring(result_ext_count)) end -- ext rows: str = str .. extRows(withStation) -- table end str = str .. tableEnd(rows_count, expectedrows)

-- cate if needCate then str = str .. cateStr end

return str end

-

local p = {}

-- for p.register = function(frame) local args = frame:getParent.args

-- 	local ingredients = {} -- list of {index, itemname, amount} for k, v in pairs(args) do		if(type(k) == 'number') then if k % 2 == 1 then -- 2n-1, nth item local index, item, amount = (k+1)/2, trim(v), trim(args[k+1]) ingredients[index] = {item, amount} end end end

local serialized = '' -- serialized ingredients list for _, v in ipairs(ingredients) do serialized = serialized .. '^' .. v[1] .. '¦' .. v[2] end serialized = mw.ustring.sub(serialized, 2)

table.sort(ingredients, function(a, b) return a[1] < b[1] end) -- sort by ingredient item name local ingredients_string = '' local ingredients_string_full = '' for _, v in ipairs(ingredients) do		local name, amount = unpack(v) local ingstr = normalize(name) ingredients_string = ingredients_string .. '^' .. ingstr ingredients_string_full = ingredients_string_full .. '^' .. ingstr .. amount end

--, normalize version = normalizeVersion(args['version'] or '')

--store frame:callParserFunction('#cargo_store:_table=Recipes',{		result = trim(args['result'] or ),		resultid = trim(args['resultid'] or ),		resultimage = trim(args['image'] or ),		resulttext = trim(args['text'] or ),		amount = trim(args['amount'] or ),		version = version,		station = normalizeStation(trim(args['station'] or )),		ingredients = mw.ustring.sub(ingredients_string, 2),		ings = mw.ustring.sub(ingredients_string_full, 2),		args = serialized,	}) end -- p.register

-- for p.query = function(frame) currentFrame = frame -- global frame cache local args = frame:getParent.args inputArgs = args

lang = frame.args['lang'] or 'en' l10n_table = l10n_info[lang] or l10n_info['en']

addCate, cateStr = (function		local cate = l10n('station_cate')		local cateCache = {}		local addCate = function(station)			cateCache[station] = true		end		local cateStr = function			local str = 			for station, _ in pairs(cateCache) do				str = str .. 			end			if str ~=  then				str =  .. str			end			return str		end		return addCate, cateStr	end)

local where = trim(args['where'] or '') if where == '' then where = criStr(args) end

-- no constraint no result. if where == '' then return ' Recipes: No constraint ' end

-- format: local needCate, needLink = getFlags(args) local needGroup = true if (getArg('grouping') or 'y'):sub(1,1) == 'n' then needGroup = false end local showResultId = false if trim(args['showresultid'] or ) ~=  then showResultId = true end local _title = trim(args['title'] or '') local _expectedrows = trim(args['expectedrows'] or '') if _expectedrows ~= '' then _expectedrows = tonumber(_expectedrows) else _expectedrows = nil end local rootpagename = mw.title.getCurrentTitle.rootText

if trim(args['nostation'] or ) ~=  then -- no station -- query, still need contain station field for cate. local result = mw.ext.cargo.query('Recipes', 'result, resultid, resultimage, resulttext, amount, version, station, args', {			where = where,			groupBy = "resultid, result, amount, version, ings",			orderBy = "result, amount DESC, version", -- Don't order by station			limit = 2000,		}) return tableBody(result, showResultId, false, needGroup, needCate, needLink, rootpagename, _title, _expectedrows, getArg('resulttemplate')) else -- with station -- query local result = mw.ext.cargo.query('Recipes', 'result, resultid, resultimage, resulttext, amount, version, station, args', {			where = where,			groupBy = "resultid, result, amount, ings, version",			orderBy = "station, result, amount DESC, version, ings", -- order by station first for station grouping.			limit = 2000,		}) return tableBody(result, showResultId, true, needGroup, needCate, needLink, rootpagename, _title, _expectedrows, getArg('resulttemplate')) end end -- p.query

-- for p.extract = function(frame) currentFrame = frame -- global frame cache

local args = frame:getParent.args inputArgs = args

lang = frame.args['lang'] or 'en' l10n_table = l10n_info[lang] or l10n_info['en']

local where = trim(args['where'] or '') if where == '' then where = criStr(args) end

-- no constraint no result. if where == '' then return ' Recipes/extract: No constraint ' end

-- query: local result = mw.ext.cargo.query('Recipes', 'result, resultid, resultimage, resulttext, amount, version, station, args', {		where = where,		groupBy = "resultid, result, amount, version, ings",		orderBy = "result, amount DESC, version", -- Don't order by station		limit = 20, -- enough.	})

-- output local mode = getArg('mode') local sep = getArg('sep') or getArg('seperator') if not mode or mode =='compact' or mode == '' then --default mode = compact local sep = sep or l10n('default_sep_compact') local withResult = getArg('withresult') local withStation = not getArg('nostation') local withVersion = not getArg('noversion') local str = nil for _, row in ipairs(result) do			if str then str = str .. sep else str = '' end str = str .. ' '			if withVersion then if row['version'] ~= '' then str = str ..currentFrame:expandTemplate{ title = 'version icons', args = {row['version']} }..': ' end end local ingFlag = nil for _, v in ipairs(explode('^', row['args'])) do				if ingFlag then str = str .. ' + '				else ingFlag = true end local item, amount = v:match('^(.-)¦(.-)$') if amount ~= '1' then str = str .. amount .. ' '				end local s				for _, itemname in ipairs(split(item)) do					if s then s = s .. "&thinsp;/&thinsp;" .. itemLink(itemname, {mode='image'}) else s = itemLink(itemname, {mode='image'}) end end str = str .. s			end if withStation then str = str .. compactStation(row['station']) end if withResult then str = str .. ' = '				if row['amount'] ~= '1' then str = str .. row['amount'] .. ' '				end local args = {mode='image'} if row['resultimage'] then args['image'] = row['resultimage'] end str = str .. itemLink(row['result'], args) end str = str..' ' end return str elseif mode == 'ingredients' then local sep = sep or l10n('default_sep_ingredients') local str = nil for _, row in ipairs(result) do			if str then str = str .. sep else str = '' end str = str .. ingredientsCell(row['args']) end return ' '..str..' ' elseif mode == 'station' then -- only return first row. for _, row in ipairs(result) do			return stationCell(row['station'], {}) end elseif mode == 'result' then -- only return first row. local needCate, needLink = getFlags(args) for _, row in ipairs(result) do			return resultCell(row, getArg('showresultid'), needLink, true, getArg('resulttemplate')) end elseif mode == 'ingredients-buy' then -- only process first row. for _, row in ipairs(result) do			local value = 0 for _, v in ipairs(explode('^', row['args'])) do				local item, amount = v:match('^(.-)¦(.-)$') value = value + require('Module:Iteminfo').getItemStat( tonumber(currentFrame:expandTemplate{ title = 'itemIdFromName', args = {item, lang='en'} }) or 0, 'value' ) * amount end return value end elseif mode == 'ingredients-sell' then -- only process first row. for _, row in ipairs(result) do			local value = 0 for _, v in ipairs(explode('^', row['args'])) do				local item, amount = v:match('^(.-)¦(.-)$') value = value + math.floor(require('Module:Iteminfo').getItemStat( tonumber(currentFrame:expandTemplate{ title = 'itemIdFromName', args = {item, lang='en'} }) or 0, 'value' )/5) * amount end return value end else return ' Recipes/extract: Invalid mode ' end end -- p.extract

-- for p.ingredientsum = function(frame) currentFrame = frame -- global frame cache

local args = frame:getParent.args inputArgs = args

lang = frame.args['lang'] or 'en' l10n_table = l10n_info[lang] or l10n_info['en'] local _versionArg = normalizeVersion(args['version'] or args['versions'] or '') local versionArg = {} if _versionArg ~= '' then versionArg = explode(' ', _versionArg) end

local where = trim(args['where'] or '') if where == '' then where = criStr(args) end

-- no constraint -> no result. if where == '' then return ' Recipes/ingredientsum: No constraint ' end

-- query: local result = mw.ext.cargo.query('Recipes', 'result, resultid, resultimage, resulttext, amount, version, station, args', {		where = where,		groupBy = "resultid, result, amount, version, ings",		orderBy = "result, amount DESC, version", -- Don't order by station		limit = 300	}) determine versions to differentiate between local versions = {} for i, resultRow in ipairs(result) do		if resultRow['version'] then local v = resultRow['version'] v = string.gsub(v, ' ', '/') if v == '' then v = currentFrame:expandTemplate{ title = 'eversions', args = {resultRow['result'], ['raw'] = 'y'} } end if v == '' then v = 'desktop/console/old-gen/mobile/3ds' end local currentVersionGroup = explode('/', v)			if next(versions) ~= nil and next(versions[next(versions)]) ~= nil then local addVersion = {} local dontAdd = false for i, versionGroup in ipairs(versions) do -- iterate over existing version groups local addVersionGroup = {} local versionsDiff= {} if identicalTables(currentVersionGroup, versionGroup) then dontAdd = true break else for j, v in ipairs(currentVersionGroup) do							for k, w in ipairs(versionGroup) do								if w == v and w ~= nil then versionsDiff[w] = { ['indexA'] = k,										['indexB'] = j									} break end end end for v, indices in pairs(versionsDiff) do							currentVersionGroup[indices['indexB']] = '' versionGroup[indices['indexA']] = '' table.insert(addVersionGroup, v)						end currentVersionGroup = removeEmptyElements(currentVersionGroup, 1) versionGroup = removeEmptyElements(versionGroup, 1) if next(addVersionGroup) ~= nil then table.insert(addVersion, addVersionGroup) end end end if (next(addVersion) == nil or next(currentVersionGroup) ~= nil) and not dontAdd then -- no overlaps or there is a currentVersion left. Add current version as it is					local addVersionGroup = {} for _, v in ipairs(currentVersionGroup) do						table.insert(addVersionGroup, v)					end table.insert(addVersion, addVersionGroup) end if next(addVersion) ~= nil then for _, v in ipairs(addVersion) do						if next(v) ~= nil then table.insert(versions, v)						end end end else -- initial table.insert(versions, currentVersionGroup) end end versions = removeEmptyElements(versions) if versions[1][1] == '' then table.remove(versions, 1) end end

get rows local str = '' local outputRows = {} -- output rows if next(versions) == nil then table.insert(versions, {'desktop', 'console', 'old-gen', 'mobile', '3ds'} ) end for h, versionGroup in ipairs(versions) do		--if subset(versionArg, versionGroup) then version = table.concat(versionGroup, ' ') if version == '' then version = 'desktop console old-gen mobile 3ds' end outputRows[version] = {} -- set query constraint for recipes of this specific version local whereCached = where if versionGroup[next(versionGroup)] ~= '' then where = where .. " AND ((version LIKE '%" for j, v in ipairs(versionGroup) do					if j ~= 1 then where = where .. "%' AND version LIKE '%" end where = where .. v				end where = where .. "%') OR version IS NULL)" end -- do query: local result = mw.ext.cargo.query('Recipes', 'result, resultid, resultimage, resulttext, amount, version, station, args', {				where = where,				groupBy = "resultid, result, amount, version, ings",				orderBy = "result, amount DESC, version", -- Don't order by station				limit = 300			}) where = whereCached -- restore constraint for next version local results = {} -- all result items that were stored in this version; used for new row checking local firstRow = true -- is this the first row of this version? for i, resultRow in ipairs(result) do -- iterate over cargo result rows local resultItem = tostring(resultRow['result']) -- skip this row if the result is not available in the current version(s) local _eversions = currentFrame:expandTemplate{ title = 'eversions', args = {resultRow['result'], ['raw'] = 'y'} } if _eversions == '' then _eversions = 'desktop/console/old-gen/mobile/3ds' end eversions = explode('/', _eversions) if subset(versionGroup, eversions) then -- check if this resultRow requires a new output row local newRow = false for j, v in ipairs(results) do						if v == resultItem then -- result is already present, add new row for it							newRow = true end end table.insert(results, resultItem) -- add current result to the list of results -- handle creation of new output row if newRow then local oldRowMaxn = table.maxn(outputRows[version]) -- cycle through current rows and duplicate them, removing the duplicate result we want to eliminate local rowsDupl = {} for j, row in ipairs(outputRows[version]) do -- fill duplicate table from source table rowsDupl[j] = {} rowDupl = rowsDupl[j] rowDupl.stations = row.stations rowDupl.ingredients = {} for k, v in pairs(row.ingredients) do								rowDupl.ingredients[k] = {} for l, w in pairs(v) do									rowDupl.ingredients[k][l] = w								end end end for _, rowDupl in ipairs(rowsDupl) do							if rowDupl.ingredients[resultItem] then rowDupl.ingredients[resultItem] = nil end end for _, v in ipairs(rowsDupl) do -- insert duplicate table into source table table.insert(outputRows[version], v)						end end -- add information to row if firstRow then -- first row of this version firstRow = false local firstRow = {} firstRow['ingredients'] = {} firstRow['stations'] = {} -- information: ingredients firstRow.ingredients[resultItem] = {} firstRow.ingredients[resultItem]['_amount'] = resultRow['amount'] -- result amount firstRow.ingredients[resultItem]['_resultid'] = resultRow['resultid'] -- resultid firstRow.ingredients[resultItem]['_resultimage'] = resultRow['resultimage'] -- resultimage firstRow.ingredients[resultItem]['_resulttext'] = resultRow['resulttext'] -- resulttext for _, v in ipairs(explode('^', resultRow['args'])) do							local item, amount = v:match('^(.-)¦(.-)$') firstRow.ingredients[resultItem][item] = amount end -- information: stations table.insert(firstRow['stations'], resultRow['station']) table.insert(outputRows[version], firstRow) -- done. else -- not the first row of this version for j, row in ipairs(outputRows[version]) do							local skip = false -- skip the first half of rows (we only want to insert this resultItem into the second half, hence why we duplicated the rows) if newRow then if j <= table.maxn(outputRows[version])/2 then skip = true end end if not skip then -- information: ingredients row.ingredients[resultItem] = {} row.ingredients[resultItem]['_amount'] = resultRow['amount'] -- result amount row.ingredients[resultItem]['_resultid'] = resultRow['resultid'] -- resultid row.ingredients[resultItem]['_resultimage'] = resultRow['resultimage'] -- resultimage row.ingredients[resultItem]['_resulttext'] = resultRow['resulttext'] -- resulttext for _, v in ipairs(explode('^', resultRow['args'])) do									local item, amount = v:match('^(.-)¦(.-)$') row.ingredients[resultItem][item] = amount end -- information: stations local stations = row['stations'] or {} local newStation = true for _, station in ipairs(stations) do									if station == resultRow['station'] then newStation = false end end if newStation then table.insert(stations, resultRow['station']) end -- done. end end end end end --end end local finalOutputRows = {} for version, versionRows in pairs(outputRows) do		for i, row in ipairs(versionRows) do			local insert = {} insert['version'] = version insert['stations'] = row.stations insert['ingredients'] = row.ingredients table.insert(finalOutputRows, insert) end end output local mode = getArg('mode') --default mode = compact local sep = getArg('sep') or getArg('separator') local withResult = getArg('withresult') local withStation = not getArg('nostation') local withVersion = not getArg('noversion') if not mode or mode =='compact' or mode == '' then local sep = sep or l10n('default_sep_compact') for i, row in ipairs(finalOutputRows) do			if subset(versionArg, explode(' ', row['version'])) then if outputStr then outputStr = outputStr .. sep else outputStr = '' end outputStr = outputStr .. ' '				-- version if withVersion then if row['version'] ~= '' and row['version'] ~= 'desktop console old-gen mobile 3ds' then -- don't print empty or full eicons outputStr = outputStr .. currentFrame:expandTemplate{ title = 'version icons', args = {row['version']} } .. ': '					end end -- ingredients local ingSum = getIngSum(row) local ingSumKeys = getIngSumKeys(ingSum) local ingFlag = nil for _, k in ipairs(ingSumKeys) do					local item = k					local amount = ingSum[k] if ingFlag then outputStr = outputStr .. ' + '					else ingFlag = true end if amount ~= '1' then outputStr = outputStr .. amount .. ' '					end local s					for _, itemname in ipairs(split(item)) do						if s then s = s .. "&thinsp;/&thinsp;" .. itemLink(itemname, {mode='image'}) else s = itemLink(itemname, {mode='image'}) end end outputStr = outputStr .. s				end -- station local stationFlag = nil if withStation then for _, station in ipairs(row['stations']) do						if station ~= 'By Hand' then if stationFlag then outputStr = outputStr .. ' + ' .. compactStation(station, '') else stationFlag = true outputStr = outputStr .. compactStation(station) end end end end -- result local resultFlag = nil if withResult then outputStr = outputStr .. ' = '					for k, v in pairs(row.ingredients) do						if resultFlag then outputStr = outputStr .. ' + '						else resultFlag = true end if v['_amount'] ~= '1' then outputStr = outputStr .. v['_amount'] .. ' '						end local args = { mode='image' } if v['_resultimage'] then args['image'] = v['_resultimage'] end outputStr = outputStr .. itemLink(k, args) end end outputStr = outputStr..' ' end end return outputStr or '' elseif mode == 'ingredients' then local sep = sep or l10n('default_sep_ingredients') local outputStr = nil for _, row in ipairs(finalOutputRows) do			if subset(versionArg, explode(' ', row['version'])) then if outputStr then outputStr = outputStr .. sep if withVersion then if row['version'] ~= '' and row['version'] ~= 'desktop console old-gen mobile 3ds' then -- don't print empty or full eicons outputStr = outputStr .. ' (' .. currentFrame:expandTemplate{ title = 'version icons', args = {row['version']} } .. ') ' end end else if withVersion then if row['version'] ~= '' and row['version'] ~= 'desktop console old-gen mobile 3ds' then -- don't print empty or full eicons outputStr = currentFrame:expandTemplate{ title = 'version icons', args = {row['version']} } .. ': '						else outputStr = '' end end end local ingSum = getIngSum(row) local ingSumKeys = getIngSumKeys(ingSum) outputStr = outputStr .. ingredientsCellIngredientSum(ingSum, ingSumKeys) end end return ' ' .. outputStr .. ' '	elseif mode == 'result' then local needCate, needLink = getFlags(args) local sep = sep or l10n('default_sep_ingredients') local outputStr = nil for _, row in ipairs(finalOutputRows) do			if subset(versionArg, explode(' ', row['version'])) then if outputStr then outputStr = outputStr .. sep else outputStr = '' end local flag = nil for resultItem, ings in pairs(row.ingredients) do					if flag then else flag = true -- version if withVersion then if row['version'] ~= '' and row['version'] ~= 'desktop console old-gen mobile 3ds' then -- don't print empty or full eicons outputStr = outputStr .. ' ' .. currentFrame:expandTemplate{ title = 'version icons', args = {row['version']} } .. ': '							end end end outputStr = outputStr .. '' outputStr = outputStr .. resultCellIngredientSum(ings, resultItem, row['version'], getArg('showresultid'), needLink, true, getArg('resulttemplate')) outputStr = outputStr .. '</ul>' end end end return ' ' .. outputStr .. ' '	elseif mode == 'station' then local sep = sep or l10n('default_sep_compact') local outputStr = nil for _, row in ipairs(finalOutputRows) do			if subset(versionArg, explode(' ', row['version'])) then if outputStr then outputStr = outputStr .. sep else outputStr = '' end local flag = nil for _, station in ipairs(row.stations) do					if flag then outputStr = outputStr .. ' + '					else flag = true -- version if withVersion then if row['version'] ~= '' and row['version'] ~= 'desktop console old-gen mobile 3ds' then -- don't print empty or full eicons outputStr = outputStr .. currentFrame:expandTemplate{ title = 'version icons', args = {row['version']} } .. ': '							end end end outputStr = outputStr .. stationCell(station, {}, true) end end end return outputStr elseif mode == 'ingredients-buy' then local value = 0 for _, row in ipairs(finalOutputRows) do			local ingSum = getIngSum(row) for item, amount in pairs(ingSum) do				value = value + require('Module:Iteminfo').getItemStat( tonumber(currentFrame:expandTemplate{ title = 'itemIdFromName', args = {item, lang='en'} }) or 0, 'value' ) * amount end end return value elseif mode == 'ingredients-sell' then local value = 0 for _, row in ipairs(finalOutputRows) do			local ingSum = getIngSum(row) for item, amount in pairs(ingSum) do				value = value + math.floor(require('Module:Iteminfo').getItemStat( tonumber(currentFrame:expandTemplate{ title = 'itemIdFromName', args = {item, lang='en'} }) or 0, 'value' )/5) * amount end end return value elseif mode == 'extract-amount' then local extractIng = getArg('ingextract') or getArg('ingredient') local outputStr = nil for _, row in ipairs(finalOutputRows) do			if subset(versionArg, explode(' ', row['version'])) then local ingSum = getIngSum(row) if ingSum[extractIng] then if outputStr then outputStr = outputStr .. ' / '					else outputStr = '' end if withVersion then if row['version'] ~= '' and row['version'] ~= 'desktop console old-gen mobile 3ds' then -- don't print empty or full eicons outputStr = outputStr .. currentFrame:expandTemplate{ title = 'version icons', args = {row['version']} } .. ' '						end end outputStr = outputStr .. ingSum[extractIng] end end end return outputStr else return currentFrame:expandTemplate{ title = 'error', args = {'Recipes/ingredientsum: Invalid mode'} } end end -- p.ingredientsum

-- count p.count = function(frame) local args = frame:getParent.args local where = trim(args['where'] or '') if where == '' then where = criStr(args) end -- no constraint no result. if where == '' then return end -- query: since we must use group by to eliminate duplicates, so we can not use COUNT to get row count directly. local result = mw.ext.cargo.query('Recipes', 'result, resultid, resultimage, resulttext, amount, version, station, args', {		where = where,		groupBy = "resultid, result, amount, ings, version",		limit = 2000,	}) -- count local count = 0 for _, row in ipairs(result) do		count = count + 1 end return count end -- p.count

-- return "yes" or "" p.exist = function(frame) local args = frame:getParent.args local where = trim(args['where'] or '') if where == '' then where = criStr(args) end -- no constraint no result. if where == '' then return end -- query: local result = mw.ext.cargo.query('Recipes', 'result', {		where = where,		limit = 1, -- enough.	}) -- output for _, row in ipairs(result) do		return 'yes' end end -- p.exist

return p