73 lines
1.9 KiB
Lua
73 lines
1.9 KiB
Lua
--- Utility functions.
|
|
-- @module advtrains_doc_integration.utils
|
|
-- @alias utils
|
|
local utils = {}
|
|
|
|
--- Create a table by applying a function to each element.
|
|
-- @tparam table tbl The table to map from.
|
|
-- @tparam function func The function to apply.
|
|
-- @treturn table The resulting table.
|
|
function utils.map(tbl, func)
|
|
local t = {}
|
|
for k, v in pairs(tbl or {}) do
|
|
t[k] = func(v)
|
|
end
|
|
return t
|
|
end
|
|
|
|
--- Create an iterator that iterates through the table in the order of
|
|
-- the keys sorted in a certain order.
|
|
-- Note that the behavior is undefined if a key is added during the iteration.
|
|
-- @tparam table tbl The table to iterate
|
|
-- @tparam[opt] function sort The function passed to @{table.sort} for
|
|
-- sorting the keys. The default sorting order is used if the function
|
|
-- is not provided.
|
|
-- @return An iterator suitable for use with Lua's `for` loop.
|
|
function utils.spairs(tbl, sort)
|
|
local keys = {}
|
|
local kn = {}
|
|
for k in pairs(tbl or {}) do
|
|
table.insert(keys, k)
|
|
end
|
|
table.sort(keys, sort)
|
|
for i = 2, #keys do
|
|
kn[keys[i-1]] = keys[i]
|
|
end
|
|
return function(t, n)
|
|
local k = kn[n]
|
|
if n == nil then
|
|
k = keys[1]
|
|
end
|
|
return k, t[k]
|
|
end, tbl, nil
|
|
end
|
|
|
|
--- Gets the name of the coupler
|
|
-- @tparam string str The technical name of the coupler
|
|
-- @treturn string The name of the coupler
|
|
function utils.get_coupler_name(str)
|
|
return advtrains.coupler_types[str]
|
|
end
|
|
|
|
--- Adjust the soundspec to table form.
|
|
-- @tparam SimpleSoundSpec spec The soundspec to adjust.
|
|
-- @treturn SimpleSoundSpec The adjusted soundspec.
|
|
function utils.adjust_soundspec(spec)
|
|
if type(spec) == "string" then
|
|
spec = {name = spec}
|
|
end
|
|
if type(spec) == "table" and spec.name and spec.name ~= "" then
|
|
return spec
|
|
end
|
|
return nil
|
|
end
|
|
|
|
--- Escape the texture string.
|
|
-- @tparam string str The texture string to escape.
|
|
-- @treturn string The escaped texture string.
|
|
function utils.texture_escape(str)
|
|
return (string.gsub(tostring(str), "[:^\\]", [[\%1]]))
|
|
end
|
|
|
|
return utils
|