Vai al contenuto

Modulo:Link list

Da Wikisource.

La documentazione per questo modulo può essere creata in Modulo:Link list/man

local p = {} --p stands for package
local getArgs = require('Module:Arguments').getArgs

-- make a "set" from a list for easy membership testing
function make_set(list)
  local set = {}
  for _, l in ipairs(list) do
  	set[l] = true
  end
  return set
end

--[=[
Format a list of links for a given range
 Arg 1: The link target format pattern
 Arg 2: The link name format pattern
 Arg 3: The range start
 Arg 4: The range end
 Arg rowlen: Break rows after this many entries
]=]
function p.link_list( frame )

	local args = getArgs(frame)
	
	local out = ""
	
	local rowlen = tonumber(args["rowlen"] or "0")
	local start = tonumber(args[3])
	local endi = tonumber(args[4])
	
	local t2_set
	if args.target2 then
		t2_set = make_set(mw.text.split(args.target2_when, ',', true))
	end
	
	local t3_set
	if args.target3 then
		t3_set = make_set(mw.text.split(args.target3_when, ',', true))
	end

    for idx = start, endi do 
    	local fsp = " "
    	local display = string.format(args[2], idx)
    	-- replace spaces in the display string with figure spaces which don't collapse in HTML

    	-- replace spaces before number with a figure space, but keep normal spaces after words
    	display = display:gsub("([^ ] |%d)( *)(%d)", function(p, s, n) return p .. s:gsub(" ", " ") .. n  end)
        --  and spaces before leading numbers
    	display = display:gsub("^( +)(%d)", function(s, n) return s:gsub(" ", " ") .. n  end)
    	
    	local target = args[1]

		-- use the alt pattern if there is one and the index is a match
    	if args.target2 and t2_set and t2_set[tostring(idx)] then
    		target = args.target2
    	end
    	
    	-- likewise for the second alt pattern
    	if args.target3 and t3_set and t3_set[tostring(idx)] then
    		target = args.target3
    	end
    	
    	-- interpolate the index in to the string
    	target = string.format(target, idx)

    	out = out .. "* [[" .. target .. "|" .. display .. "]]\n"
    	
    	-- add an extra line break after "rowlen" items, if rowlen is set
    	if rowlen > 0 and ((idx - start + 1) % rowlen == 0) and idx ~= endi then
    		out = out .. "\n"
    	end
    end

	return out
end

return p