ui_imagecollection.lua 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. local l_gfx = love.graphics
  2. -- This undrawable element is a collection for image resource
  3. -- The thing is - it will try not to repeat resource creation if you try to get something from it, instead giving a reference on already created resource
  4. ImageCollection = {}
  5. ImageCollection.__index = ImageCollection
  6. ImageCollection.ident = "ui_imagecollection"
  7. ImageCollection.name = "ImageCollection"
  8. function ImageCollection:new(name)
  9. local self = {}
  10. setmetatable(self,ImageCollection)
  11. self.items = {}
  12. if name ~= nil then self.name = name end
  13. return self
  14. end
  15. setmetatable(ImageCollection,{__index = Element})
  16. function ImageCollection:addItem(image,name)
  17. local c = self:getCount()
  18. if c>0 then
  19. for i=1,c do
  20. if self.items[i][2] == name then
  21. return self.items[i][1]
  22. end
  23. end
  24. local name = name or (#self.items+1)
  25. local img = l_gfx.newImage(image)
  26. table.insert(self.items,{img,name})
  27. return img
  28. else
  29. local name = name or (#self.items+1)
  30. local img = l_gfx.newImage(image)
  31. table.insert(self.items,{img,name})
  32. return img
  33. end
  34. end
  35. function ImageCollection:getItem(item)
  36. if type(item) == "number" then
  37. return self.items[item][1],self.items[item][2]
  38. elseif type(item) == "string" then
  39. local c = self:getCount()
  40. if c>0 then
  41. for i=1,c do
  42. if self.items[i][2] == item then
  43. return self.items[i][1],self.items[i][2]
  44. end
  45. end
  46. end
  47. end
  48. return nil
  49. end
  50. function ImageCollection:getCount()
  51. return #self.items
  52. end