cargo.lua 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. -- cargo v0.1.0
  2. -- https://github.com/bjornbytes/cargo
  3. -- MIT License
  4. local cargo = {}
  5. local function merge(target, source, ...)
  6. if not target or not source then return target end
  7. for k, v in pairs(source) do target[k] = v end
  8. return merge(target, ...)
  9. end
  10. local la, lf, lg = love.audio, love.filesystem, love.graphics
  11. local function makeFont(path)
  12. return function(size)
  13. return lg.newFont(path, size)
  14. end
  15. end
  16. local function loadFile(path)
  17. return lf.load(path)()
  18. end
  19. cargo.loaders = {
  20. lua = lf and loadFile,
  21. png = lg and lg.newImage,
  22. jpg = lg and lg.newImage,
  23. dds = lg and lg.newImage,
  24. glsl = lg and lg.newShader,
  25. mp3 = la and la.newSource,
  26. ogg = la and la.newSource,
  27. wav = la and la.newSource,
  28. txt = lf and lf.read,
  29. ttf = lg and makeFont
  30. }
  31. cargo.processors = {}
  32. function cargo.init(config)
  33. if type(config) == 'string' then
  34. config = {dir = config}
  35. end
  36. local loaders = merge({}, cargo.loaders, config.loaders)
  37. local processors = merge({}, cargo.processors, config.processors)
  38. local init
  39. local function halp(t, k)
  40. local path = (t._path .. '/' .. k):gsub('^/+', '')
  41. if lf.isDirectory(path) then
  42. rawset(t, k, init(path))
  43. return t[k]
  44. else
  45. for extension, loader in pairs(loaders) do
  46. local file = path .. '.' .. extension
  47. if loader and lf.exists(file) then
  48. local asset = loader(file)
  49. rawset(t, k, asset)
  50. for pattern, processor in pairs(processors) do
  51. if file:match(pattern) then
  52. processor(asset, file, t)
  53. end
  54. end
  55. return asset
  56. end
  57. end
  58. end
  59. return rawget(t, k)
  60. end
  61. init = function(path)
  62. return setmetatable({_path = path}, {__index = halp})
  63. end
  64. return init(config.dir)
  65. end
  66. return cargo