cargo.lua 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. -- cargo v0.1.1
  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. ogv = lg and lg.newVideo,
  25. glsl = lg and lg.newShader,
  26. mp3 = la and la.newSource,
  27. ogg = la and la.newSource,
  28. wav = la and la.newSource,
  29. txt = lf and lf.read,
  30. ttf = lg and makeFont
  31. }
  32. cargo.processors = {}
  33. function cargo.init(config)
  34. if type(config) == 'string' then
  35. config = {dir = config}
  36. end
  37. local loaders = merge({}, cargo.loaders, config.loaders)
  38. local processors = merge({}, cargo.processors, config.processors)
  39. local init
  40. local function halp(t, k)
  41. local path = (t._path .. '/' .. k):gsub('^/+', '')
  42. if lf.isDirectory(path) then
  43. rawset(t, k, init(path))
  44. return t[k]
  45. else
  46. for extension, loader in pairs(loaders) do
  47. local file = path .. '.' .. extension
  48. if loader and lf.exists(file) then
  49. local asset = loader(file)
  50. rawset(t, k, asset)
  51. for pattern, processor in pairs(processors) do
  52. if file:match(pattern) then
  53. processor(asset, file, t)
  54. end
  55. end
  56. return asset
  57. end
  58. end
  59. end
  60. return rawget(t, k)
  61. end
  62. init = function(path)
  63. return setmetatable({_path = path}, {__index = halp})
  64. end
  65. return init(config.dir)
  66. end
  67. return cargo