Module:Harmonics intro
Documentation for this module may be created at Module:Harmonics intro/doc
-- Module:Harmonics intro
-- Generates the opening sentences of the "Harmonics n–2n" and "Subharmonics n–2n" pages.
-- Called through Template:Harmonics intro and Template:Subharmonics intro.
local p = {}
local getArgs = require("Module:Arguments").getArgs
local EN_DASH = "–"
-- "n:(n+1):…:2n", written out in full for small n
local function chord(lo, hi)
if hi - lo <= 7 then
local t = {}
for i = lo, hi do
t[#t + 1] = i
end
return table.concat(t, ":")
end
return string.format("%d:%d:…:%d", lo, lo + 1, hi)
end
local function page_exists(title)
local t = mw.title.new(title)
return t ~= nil and t.exists
end
local function build(args, sub)
local n = tonumber(args[1] or args.n)
if not n or n < 1 or n ~= math.floor(n) then
return '<strong class="error">Template:Harmonics intro requires a positive integer, e.g. <code>{{Harmonics intro|12}}</code>.</strong>'
end
local base = sub and "Subharmonics" or "Harmonics"
local twin = sub and "Harmonics" or "Subharmonics"
local title = string.format("%s %d%s%d", base, n, EN_DASH, 2 * n)
local twin_title = string.format("%s %d%s%d", twin, n, EN_DASH, 2 * n)
-- first sentence
local bold = "'''" .. title .. "'''"
local akas = {}
for name in mw.text.gsplit(args.aka or "", "%s*;%s*") do
if name ~= "" then
akas[#akas + 1] = "'''" .. name .. "'''"
end
end
local aka = ""
if #akas > 0 then
aka = ", also known as " .. table.concat(akas, " and ") .. ","
end
local out = {}
if sub then
out[#out + 1] = string.format(
"%s%s is the scale formed by the [[subharmonic]]s %d through %d of the [[subharmonic series]], that is, the ratios %d/%d, %d/%d, …, %d/%d above the root. ",
bold, aka, n, 2 * n, 2 * n, 2 * n, 2 * n, 2 * n - 1, 2 * n, n)
else
out[#out + 1] = string.format(
"%s%s is the [[Harmonic series#Segments|harmonic segment]] %d::%d, consisting of harmonics %d through %d (%s) and spanning one octave above the root. ",
bold, aka, n, 2 * n, n, 2 * n, chord(n, 2 * n))
end
-- second sentence: mode name
out[#out + 1] = string.format("It is also called mode %d of the %s series. ", n, sub and "subharmonic" or "harmonic")
-- inverse
if page_exists(twin_title) then
out[#out + 1] = string.format("Its inverse is [[%s]]. ", twin_title)
end
return (table.concat(out):gsub("%s+$", ""))
end
function p.harmonics(frame)
return build(getArgs(frame), false)
end
function p.subharmonics(frame)
return build(getArgs(frame), true)
end
p._build = build
return p