Модуль:RandomPageFromCategory: различия между версиями

Материал из Поле цифровой дидактики
Нет описания правки
Нет описания правки
 
(не показаны 2 промежуточные версии этого же участника)
Строка 1: Строка 1:
-- Module:RandomPageFromCategory
local p = {}
local p = {}


local function pick(list)
math.randomseed(os.time())
  if #list == 0 then
 
    return nil
local function pickOne(t)
  end
    if not t or #t == 0 then
  math.randomseed(os.time())
        return nil
  return list[math.random(#list)]
    end
    return t[math.random(#t)]
end
end


function p.fromCategory(frame)
function p.getRandomTitle(category)
  local cat = frame.args[1] or "Book"
    if not mw.smw then
  return "[[Special:RandomInCategory/" .. cat .. "|случайная страница из " .. cat .. "]]"
        return nil, "Ошибка: mw.smw недоступен"
    end
 
    if not category or category == "" then
        category = "Book"
    end
 
    local results = mw.smw.ask({
        string.format('[[Category:%s]]', category),
        '?#-=title',
        'limit=200'
    })
 
    if not results or #results == 0 then
        return nil, "В категории нет страниц: " .. category
    end
 
    local item = pickOne(results)
 
    if type(item) == "table" then
        return item.title or item[1] or nil, nil
    end
 
    return item, nil
end
end


function p.fromList(frame)
function p.main(frame)
  local items = {}
    local category = frame.args.category or frame.args[1] or "Book"
  local i = 1
     local title, err = p.getRandomTitle(category)
  while frame.args[i] do
    table.insert(items, frame.args[i])
     i = i + 1
  end


  local page = pick(items)
    if not title or title == "" then
  if not page then
        return err or "Не удалось получить название страницы"
    return "Нет страниц в списке"
    end
  end


  return page
    return title
end
end


return p
return p

Текущая версия от 07:48, 21 мая 2026


local p = {}

math.randomseed(os.time())

local function pickOne(t)
    if not t or #t == 0 then
        return nil
    end
    return t[math.random(#t)]
end

function p.getRandomTitle(category)
    if not mw.smw then
        return nil, "Ошибка: mw.smw недоступен"
    end

    if not category or category == "" then
        category = "Book"
    end

    local results = mw.smw.ask({
        string.format('[[Category:%s]]', category),
        '?#-=title',
        'limit=200'
    })

    if not results or #results == 0 then
        return nil, "В категории нет страниц: " .. category
    end

    local item = pickOne(results)

    if type(item) == "table" then
        return item.title or item[1] or nil, nil
    end

    return item, nil
end

function p.main(frame)
    local category = frame.args.category or frame.args[1] or "Book"
    local title, err = p.getRandomTitle(category)

    if not title or title == "" then
        return err or "Не удалось получить название страницы"
    end

    return title
end

return p