lua-rtos-libs/libs/utils.lua

93 lines
2.3 KiB
Lua

local M = {}
function M.printTable(t, indent)
indent = indent or ""
for key, value in pairs(t) do
if type(value) == "table" then
print(indent .. tostring(key) .. ":")
M.printTable(value, indent .. " ")
else
print(indent .. tostring(key) .. ": " .. tostring(value))
end
end
end
function M.sliceTable(tbl, first, last)
local sliced = {}
for i = first or 1, last or #tbl do
sliced[#sliced + 1] = tbl[i]
end
return sliced
end
function M.compareSlices(slice1, slice2)
if #slice1 ~= #slice2 then
return false
end
for i = 1, #slice1 do
if slice1[i] ~= slice2[i] then
return false
end
end
return true
end
function M.profile(func, ...)
local startTime = os.clock()
func(...)
local endTime = os.clock()
return endTime - startTime
end
local function bytesToHumanReadable(bytes)
local units = {"B", "KB", "MB"}
local scale = 1024
local unit = 1
while bytes > scale and unit < #units do
bytes = bytes / scale
unit = unit + 1
end
return string.format("%.2f %s", bytes, units[unit])
end
function M.df(path)
local diskfree, disktotal = os.df(path)
local diskused = disktotal - diskfree
local usePercentage = (diskused / disktotal) * 100
local sizeHR = bytesToHumanReadable(disktotal)
local usedHR = bytesToHumanReadable(diskused)
local freeHR = bytesToHumanReadable(diskfree)
local headerFormat = "%-15s %-15s %-15s %-15s %-15s"
local rowFormat = "%-15s %-15s %-15s %-15s %-15s"
print(string.format(headerFormat, "Size", "Used", "Avail", "Use%", "Mounted"))
print(string.format(rowFormat, sizeHR, usedHR, freeHR, string.format("%.2f%%", usePercentage), path))
end
function M.adjustTz(timeFormat, timeOffset)
local utcTime = os.time()
local adjustedTime = utcTime + (timeOffset * 3600)
return os.date(timeFormat, adjustedTime)
end
-- call cb every N seconds. if cb == nil, return true
function M.routine(interval_s, cb)
local cb = cb or function() return true end
local last_time = os.time()
return function()
local current_time = os.time()
if current_time - last_time >= interval_s then
last_time = current_time
return cb()
end
end
end
return M