Модуль:Песочница/CatBG: различия между версиями
Материал из Space Station 14 Вики
CatBG (обсуждение | вклад) Нет описания правки |
CatBG (обсуждение | вклад) Нет описания правки |
||
| (не показана 1 промежуточная версия этого же участника) | |||
| Строка 17: | Строка 17: | ||
local total_seconds | local total_seconds | ||
-- | -- Сначала пробуем распарсить как "10h" | ||
local parsed = parse_hours_string(value) | local parsed = parse_hours_string(value) | ||
if parsed ~= nil then | if parsed ~= nil then | ||
total_seconds = parsed | total_seconds = parsed | ||
else | else | ||
-- | -- Иначе — как число (старая логика) | ||
local num = tonumber(value) | local num = tonumber(value) | ||
total_seconds = (num and ((mode == "minutes") and num * 60 or num)) or 0 | |||
end | end | ||
local hours = math.floor(total_seconds / 3600) | local hours = math.floor(total_seconds / 3600) | ||
local minutes = math.floor((total_seconds % 3600) / 60) | local minutes = math.floor((total_seconds % 3600) / 60) | ||
local seconds = math.floor(total_seconds + 0.5) % 60 -- | local seconds = math.floor(total_seconds + 0.5) % 60 -- для корректного округления дробей | ||
local parts = {} | local parts = {} | ||
| Строка 52: | Строка 48: | ||
local args = frame.args | local args = frame.args | ||
local mode = args[1] or "seconds" | local mode = args[1] or "seconds" | ||
local value = | local value = args[2] or 0 -- важно: не tonumber здесь! | ||
return format_time(mode, value) | return format_time(mode, value) | ||
Текущая версия от 16:28, 10 ноября 2025
Для документации этого модуля может быть создана страница Модуль:Песочница/CatBG/doc
local p = {}
-- Парсим строки вида "10h", "2.5h" → секунды
local function parse_hours_string(s)
if type(s) ~= "string" then return nil end
local h = s:match("^%s*([%d.]+)%s*[hH]%s*$")
if h then
local num = tonumber(h)
if num then
return num * 3600
end
end
return nil
end
local function format_time(mode, value)
local total_seconds
-- Сначала пробуем распарсить как "10h"
local parsed = parse_hours_string(value)
if parsed ~= nil then
total_seconds = parsed
else
-- Иначе — как число (старая логика)
local num = tonumber(value)
total_seconds = (num and ((mode == "minutes") and num * 60 or num)) or 0
end
local hours = math.floor(total_seconds / 3600)
local minutes = math.floor((total_seconds % 3600) / 60)
local seconds = math.floor(total_seconds + 0.5) % 60 -- для корректного округления дробей
local parts = {}
if hours > 0 then
table.insert(parts, hours .. " час.")
end
if minutes > 0 then
table.insert(parts, minutes .. " мин.")
end
if seconds > 0 or #parts == 0 then
table.insert(parts, seconds .. " сек.")
end
return table.concat(parts, " ")
end
function p.main(frame)
local args = frame.args
local mode = args[1] or "seconds"
local value = args[2] or 0 -- важно: не tonumber здесь!
return format_time(mode, value)
end
return p