Module:NPCShop: Difference between revisions
Create NPCShop Lua module with correct content model (via create-page on MediaWiki MCP Server) Tag: Recreated |
Include == Shop == header in output when items exist, return empty when no items (via update-page on MediaWiki MCP Server) |
||
| Line 33: | Line 33: | ||
}) | }) | ||
-- Return empty if no shop items (section won't display) | |||
if not items or #items == 0 then | if not items or #items == 0 then | ||
return ' | return '' | ||
end | end | ||
| Line 79: | Line 80: | ||
end | end | ||
return tostring(tbl) | -- Return section header + table | ||
return '== Shop ==\n' .. tostring(tbl) | |||
end | end | ||
return p | return p | ||
Revision as of 20:06, 30 January 2026
Documentation for this module may be created at Module:NPCShop/doc
local p = {}
-- Get sprite for an item from Cargo, fallback to item name
local function getItemSprite(itemName)
local result = mw.ext.cargo.query('Items', 'sprite', {
where = 'name="' .. itemName .. '"',
limit = 1
})
if result and result[1] and result[1].sprite and result[1].sprite ~= '' then
return result[1].sprite
end
return itemName
end
-- Format cost display
local function formatCost(cost, currency)
if not cost or cost == '' then
return '?'
end
local curr = currency or 'Gold'
return tostring(cost) .. ' ' .. curr
end
-- Main function to display NPC shop items
function p.display(frame)
local args = frame:getParent().args
local source = args.npc or args.source or mw.title.getCurrentTitle().text
-- Query ItemSource for shop items
local items = mw.ext.cargo.query('ItemSource', 'item,cost,currency', {
where = 'source="' .. source .. '" AND source_type="shop"'
})
-- Return empty if no shop items (section won't display)
if not items or #items == 0 then
return ''
end
-- Sort by cost ascending
table.sort(items, function(a, b)
local costA = tonumber(a.cost) or 0
local costB = tonumber(b.cost) or 0
return costA < costB
end)
-- Build table using mw.html
local tbl = mw.html.create('table')
:addClass('wikitable')
:addClass('sortable')
:addClass('shop-table')
-- Header row
local headerRow = tbl:tag('tr')
headerRow:tag('th'):addClass('unsortable'):wikitext('')
headerRow:tag('th'):wikitext('Item')
headerRow:tag('th'):wikitext('Cost')
for _, item in ipairs(items) do
local sprite = getItemSprite(item.item)
local costDisplay = formatCost(item.cost, item.currency)
local costValue = tonumber(item.cost) or 0
local row = tbl:tag('tr')
-- Sprite cell
local spriteWikitext = frame:preprocess(string.format('{{Sprite|%s|x2}}', sprite))
row:tag('td')
:css('text-align', 'center')
:wikitext(spriteWikitext)
-- Item cell
row:tag('td')
:wikitext(string.format('[[%s]]', item.item))
-- Cost cell with sort value
row:tag('td')
:attr('data-sort-value', costValue)
:wikitext(costDisplay)
end
-- Return section header + table
return '== Shop ==\n' .. tostring(tbl)
end
return p