elua/util.lua

50 lines
1.2 KiB
Lua
Raw Normal View History

---
---Print a formatted string. Put `{}` where you want something to be formatted in its place.
---
---```lua
---local yummy_food = "chips"
---printf("Lets eat {} together!", yummy_food)
---```
---
---The items provided in the variable arguments must implement `tostring`!
---
---@param str string
---@param ... any
function printf(str, ...)
local fleft, fright = str:find("{}")
local formatted = ""
-- current vararg index
local arg = 1
while (fleft ~= nil and fright ~= nil) do
formatted = formatted .. str:sub(0, fleft - 1)
formatted = formatted .. tostring(select(arg, ...))
str = str:sub(fright + 1, str:len())
fleft, fright = str:find("{}")
arg = arg + 1
end
formatted = formatted .. str
print(formatted)
end
---
---Recursively dumps a table as a string.
---
---@param obj table
---@return string
---@nodiscard
function dump_table(obj)
if type(obj) == 'table' then
local s = '{ '
for k,v in pairs(obj) do
if type(k) ~= 'number' then k = '"'..k..'"' end
s = s .. '['..k..'] = ' .. dump_table(v) .. ','
end
return s .. '} '
else
return tostring(obj)
end
end