このモジュールについての説明文ページを モジュール:jiscode/doc に作成できます

local export = {}

-- 面区点から水準を返す
local level = function (m, k, t)
    if (m == 2) then
        -- 2面のうちJIS X 0212に該当するもの
        for _,e in pairs({{2}, {6, 7}, {9, 11}, {16, 77}}) do
            e[2] = e[2] or e[1];
            if ((e[1] <= k) and (k <= e[2])) then return -1; end
        end
        -- 2面の残りが第4水準
        return 4;
    end

    -- 1面のうち第3水準に該当するもの
    for _,e in pairs({{9, 15}, {85, 94}}) do
        if (e[1] <= k) and (k <= e[2]) then return 3; end
    end
    local level3t = ({
        [2] = {{15,25}, {34,41}, {49,59}, {75,81}, {90,93}},
        [3] = {{1,15}, {26,32}, {59,64}, {91,94}},
        [4] = {{84,91}},
        [5] = {{87,94}},
        [6] = {{25,32}, {57,94}},
        [7] = {{34,48}, {82,94}},
        [8] = {{33,62}, {71,92}},
        [47] = {{52,94}},
        [84] = {{07,94}},
    });
    for _,e in pairs(level3t[k] or {}) do
        if ((e[1] <= t) and (t <= e[2])) then return 3; end
    end

    -- 1面の残りが第1・第2水準
    return (k < 48) and 1 or 2;
end

function export.encoding(frame)
    local m,k,t = frame.args[1]:match("(%d+)-(%d+)-(%d+)")
    m = tonumber(m) or 1
    k = tonumber(k) or 1
    t = tonumber(t) or 1

    local euc = function (m, k, t)
        return ((k + 0xa0) * 0x100 + (t + 0xa0) + (m == 2 and 0x8f0000 or 0))
    end
    local iso2022 = function (m, k, t)
       return (k + 0x20) * 0x100 + (t + 0x20);
    end

    local sjis = function(m, k, t)
        local seq = (k - 1) * 94 + (t - 1);
        local c1 = math.floor(seq / 188);
        local c2 = seq % 188;
        local p2 = (function(m, k)
          if (m ~= 2) then return 0; end
          if (k <= 5) then return 0x6f; end
          if (k <= 15) then return 0x6c; end
          return 0xd;
        end)(m, k);
        return (c1 + (c1 < 31 and 129 or 193) + p2) * 0x100 + c2 + (c2 < 63 and 64 or 65);
    end
    local l = level(m,k,t);

    local encode = {};
    if (0 < l) then table.insert(encode, ("[[Shift_JIS]]=<code>0x%x</code>, "):format(sjis(m,k,t))) end
    table.insert(encode, ("[[EUC]]-JP=<code>0x%x<code>, "):format(euc(m,k,t)))
    table.insert(encode, ("ISO-2022-JP=<code>0x%x</code>"):format(iso2022(m,k,t)))

    return (("*%s: %d面%d区%d点 %s <br/> (%s)"):format(
        l < 0 and "JIS X 0212" or l <= 2 and "JIS X 0208" or "JIS X 0213",
        m, k, t,
        l < 0 and "" or ("[第%d水準]"):format(l),
        table.concat(encode)
    ));
end

return export