Jump to content

Module:TableCSV

Unchecked
From Wikipedia

Documentation for this module may be created at Module:TableCSV/doc

local p = {}

function p.error(message)
  return '<strong class="error">エラー:' .. message .. '</strong>'
end

function p.main(frame)
  local args = require('Module:Arguments').getArgs(frame, {
    wrappers = 'Template:TableCSV', -- trim = false, removeBlanks = false
  })
  local csv = args.csv or ''
  -- 属性
  local cls = args.cls and 'class="' .. args.cls .. '" ' or ''
  local id = args.id and 'id="' .. args.id .. '" ' or ''
  local css = args.css and 'style="' .. args.css .. '" ' or ''

  local thArgsDirection = { 'Left', 'Top', 'Right', 'Bottom' }
  local thArgs = {}

  -- テーブルヘッダー引数らの設定
  for i, thArgDirec in pairs(thArgsDirection) do
    local thArgStr = args['th' .. thArgDirec] or '0'
    local thArg = tonumber(thArgStr)
    thArgs[thArgDirec:lower()] = thArg ~= nil and thArg or 0
  end
  
  local body = ''

  -- csvを一旦2次元配列にする
  local tbl = {}
  local row = {}
  local rowIdx = 1
  for line, lf in csv:gmatch '([^\n]+)(\n*)' do
    row.lf = lf
    local colIdx = 1
    local isLast = false
    for cell, comma in line:gmatch '([^,]*)(,?)' do
      -- セルの情報をrowに溜める
      if not isLast then row[colIdx] = cell end
      isLast = #comma == 0
      colIdx = colIdx + 1
    end
    -- 1行分の情報をtblの末尾に追加
    if 0 < #row then table.insert(tbl, row) end
    row = {}
    rowIdx = rowIdx + 1
  end

  for rowIdx, row in pairs(tbl) do
    local tblTop = (rowIdx == 1 and args.cap and '|+' .. args.cap) or '|-'
    local wikiTblLf = row.lf ~= nil and tblTop or ''
    body = body .. wikiTblLf .. '\n'
    for colIdx, cell in pairs(row) do
      if tonumber(colIdx) == nil then break end
      local wikiTblSep = colIdx == 1 and '|' or '||'
      local isThLeft = colIdx <= thArgs.left
      local isThVertical = rowIdx <= thArgs.top or #tbl - rowIdx < thArgs.bottom
      local isThHorizontal = isThLeft or #row - colIdx < thArgs.right
      local isTh = isThVertical or isThHorizontal
      wikiTblSep = isTh and wikiTblSep:gsub('|', '!') or wikiTblSep
      local thLfBefore = isThHorizontal and '\n' or ''
      local thLfAfter = isThLeft and not isThVertical and '\n' or ''
      wikiTblSep = isThHorizontal and '!' or wikiTblSep
      body = body .. thLfBefore .. wikiTblSep .. cell .. thLfAfter
    end
    body = body .. '\n'
  end

  return '{| ' .. cls .. id .. css .. '\n' .. body .. '|}'
end

return p