「第2回エンペディア大賞」が2月いっぱい開催中です。2024年に作成された記事の中から、お気に入りの記事に投票しましょう!
モジュール:TableUtil
ナビゲーションに移動
検索に移動
local p = {}
-- 二次元配列をWikiテーブル文字列に変換
function p.arr2DToWikiTbl(args)
local tbl = args[1] or {}
local cls = args.cls and #args.cls>0 and 'class="' .. args.cls .. '" ' or ''
local id = args.id and #args.id>0 and 'id="' .. args.id .. '" ' or ''
local css = args.css and #args.css>0 and 'style="' .. args.css .. '" ' or ''
-- 左右上下を何行/列だけ表ヘッダーとするか
local thLeft = args.thLeft or 0
local thRight = args.thRight or 0
local thTop = args.thTop or 0
local thBottom = args.thBottom or 0
local body = ''
for rowIdx, row in pairs(tbl) do
-- 表タイトルが指定されたら「|+ タイトル」、未指定なら「|-」
local sepRow = (rowIdx == 1 and args.cap and #args.cap>0 and '|+' .. args.cap) or '|-'
body = body .. sepRow .. '\n'
local isThPrev = false
for colIdx, cell in pairs(row) do
if tonumber(colIdx) == nil then break end
-- isTh(テンプレユーザがヘッダーセルに指定したか)判定
local isThLeft = colIdx <= thLeft -- (エイリアス)
local isThRow = rowIdx <= thTop or #tbl - rowIdx < thBottom -- ヘッダー行か
local isThColumn = isThLeft or #row - colIdx < thRight -- ヘッダー列か
local isTh = isThRow or isThColumn
-- 1つ前のセルと現在のセルについて、片方がヘッダーセル、片方が普通のセル ならTrue
local isDifCellType = (isThPrev and not isTh) or (not isThPrev and isTh)
-- 前方で改行する必要があるか
local isLfBefore = isDifCellType and colIdx ~= 1
-- セル内容の前方セパレート字句
-- 行頭(違うセルタイプに切り替わる)なら|、途中(同じセルタイプが続く)なら||
local sep = isDifCellType and '|' or '||'
-- ヘッダーセルの場合は | → ! に置換
sep = isTh and sep:gsub('|', '!') or sep
-- cellの内容……改行を<br>に置き換え
body = body..(isLfBefore and '\n' or '')..sep..cell:gsub('\n', '<br>', 1, true)
isThPrev = isTh
end
body = body..'\n'
end
return '{| '..cls..id..css..'\n'..body..'|}'
end
return p