utils.lua 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. --- Utility functions.
  2. -- @module advtrains_doc_integration.utils
  3. -- @alias utils
  4. local utils = {}
  5. --- Create a table by applying a function to each element.
  6. -- @tparam table tbl The table to map from.
  7. -- @tparam function func The function to apply.
  8. -- @treturn table The resulting table.
  9. function utils.map(tbl, func)
  10. local t = {}
  11. for k, v in pairs(tbl or {}) do
  12. t[k] = func(v)
  13. end
  14. return t
  15. end
  16. --- Create an iterator that iterates through the table in the order of
  17. -- the keys sorted in a certain order.
  18. -- Note that the behavior is undefined if a key is added during the iteration.
  19. -- @tparam table tbl The table to iterate
  20. -- @tparam[opt] function sort The function passed to @{table.sort} for
  21. -- sorting the keys. The default sorting order is used if the function
  22. -- is not provided.
  23. -- @return An iterator suitable for use with Lua's `for` loop.
  24. function utils.spairs(tbl, sort)
  25. local keys = {}
  26. local kn = {}
  27. for k in pairs(tbl or {}) do
  28. table.insert(keys, k)
  29. end
  30. table.sort(keys, sort)
  31. for i = 2, #keys do
  32. kn[keys[i-1]] = keys[i]
  33. end
  34. return function(t, n)
  35. local k = kn[n]
  36. if n == nil then
  37. k = keys[1]
  38. end
  39. return k, t[k]
  40. end, tbl, nil
  41. end
  42. --- Gets the name of the coupler
  43. -- @tparam string str The technical name of the coupler
  44. -- @treturn string The name of the coupler
  45. function utils.get_coupler_name(str)
  46. return advtrains.coupler_types[str]
  47. end
  48. --- Adjust the soundspec to table form.
  49. -- @tparam SimpleSoundSpec spec The soundspec to adjust.
  50. -- @treturn SimpleSoundSpec The adjusted soundspec.
  51. function utils.adjust_soundspec(spec)
  52. if type(spec) == "string" then
  53. spec = {name = spec}
  54. end
  55. if type(spec) == "table" and spec.name and spec.name ~= "" then
  56. return spec
  57. end
  58. return nil
  59. end
  60. --- Escape the texture string.
  61. -- @tparam string str The texture string to escape.
  62. -- @treturn string The escaped texture string.
  63. function utils.texture_escape(str)
  64. return (string.gsub(tostring(str), "[:^\\]", [[\%1]]))
  65. end
  66. return utils