Модуль:RandomPageFromCategory

Материал из Поле цифровой дидактики

-- Module:RandomPageFromCategory
local p = {}

function p.fromCategory(frame)
  local cat = frame.args[1] or "Book"

  -- mw.smw.ask принимает таблицу параметров точно как #ask
  local query = {
    "[[Category:" .. cat .. "]]",
    mainlabel = "title",
    limit = "500"
  }

  local res = mw.smw.ask(query)

  -- отладка: показать что вернул запрос
  if not res then
    return "mw.smw.ask вернул nil для категории: " .. cat
  end
  if type(res) == "string" then
    return "Ошибка запроса: " .. res
  end
  if #res == 0 then
    return "Пустой результат для категории: " .. cat
  end

  -- случайный элемент
  math.randomseed(os.clock() * 100000)
  local row = res[ math.random(1, #res) ]

  -- заголовок лежит в поле "title" (наш mainlabel)
  local title = row.title or row[1]
  if not title then
    -- показать что реально пришло, для отладки
    local keys = {}
    for k, v in pairs(row) do
      table.insert(keys, tostring(k) .. "=" .. tostring(v))
    end
    return "Нет title. Поля: " .. table.concat(keys, ", ")
  end

  return "[[" .. title .. "]]"
end

return p