Module:Card/traits/accepts image input

From Yugipedia
Jump to: navigation, search
--[[
  Add this trait to card modules that require card images to be manually input
  as opposed to modules that add the card images automatically.
]]--
-- Allow this to be tested in the debug console.
if not Card then
	Card = require('Module:Card')
end

-- Take a copy of the original `Card` object before this makes changes to it.
local Parent = mw.clone(Card)

-- ------------------------------------
-- Override methods
--    These methods exist in the original `Card` module
--    And are having their behavior modified here.
-- ------------------------------------
-- Override the `setData` method to include sets
function Card:setData(args)
	-- Call the original `setData` function
	Parent.setData(self, args)

	-- Add image data based on the input
	self:setImages(args.image)

	-- Add an image of the backing if one is provided
	if (args.back_image) then
		self.hasCustomBacking = true

		table.insert(self.images, {
			image  = args.back_image,
			name   = 'Back',
			isBack = true
		})
	end
end

-- ------------------------------------
-- New methods
--    Modify the card module to have these extra methods
-- ------------------------------------
-- Set images data based on the input parameter
-- @param string input
function Card:setImages(input)
	-- Clear existing value
	self.images = {}

	-- Split input by new line for multiple artworks
	local inputLines = mw.text.split((input or ''), '\n')

	local previousArtwork = nil

	-- For each line (artwork)
	for _, line in pairs(inputLines) do
		-- Ensure each item on the line ends with `;` to help pattern matching
		line = line .. ';'

		-- Content before first `;` is the image
		local image     = mw.text.split(line, ';')[1]

		-- Content after `artwork::` in the params string is the artwork number.
		-- Defaults to 1
		local artwork   = tonumber(line:match('; *artwork::([^;]-) *;') or 1)

		-- Content after `thumb::` in the params string is the thumbnail
		-- Defaults to the full image
		local thumbnail = line:match('; *thumb::([^;]-) *;') or image

		-- Content after `name::` in the params string is the artwork name
		local name      = line:match('; *name::([^;]-) *;')

		-- If the params string contains `current`, mark as the current image
		local isCurrent = line:match('; *current *;') ~= nil

		-- If the artwork has the same base number as its predecessor
		-- its number is .1 higher than it
		if (previousArtwork ~= nil and math.floor(artwork) == math.floor(previousArtwork)) then
			artwork = previousArtwork + .1
		end

		-- Add object to list of images
		table.insert(self.images, {
			image     = image,
			thumbnail = thumbnail,
			artwork   = artwork,
			name      = name,
			isCurrent = isCurrent
		})

		-- Prepare for the next iteration of the loop.
		previousArtwork = artwork
	end
end

-- Allow this to be tested in the debug console.
return Card