ui_collection.lua 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. -- undrawable container element
  2. -- you can hold stuff in it, strings, numbers, tables, userdata etc
  3. -- has simple adding, deleting and getting interface
  4. -- UIManager's version of an array
  5. Collection = {}
  6. Collection.__index = Collection
  7. Collection.ident = "ui_collection"
  8. Collection.name = "Collection"
  9. Collection.updateable = false
  10. Collection.input = false
  11. Collection.drawable = false
  12. function Collection:new(name)
  13. local self = {}
  14. setmetatable(self,Collection)
  15. self.items = {}
  16. if name ~= nil then self.name = name end
  17. return self
  18. end
  19. setmetatable(Collection,{__index = Element})
  20. -- adds element into collection and fires onadd event
  21. function Collection:addItem(item)
  22. table.insert(self.items,item)
  23. self:onadd()
  24. end
  25. -- if element is a table or userdata, you will receive a reference to it, in other cases you will create duplicate of that element in your variable
  26. function Collection:getItem(index)
  27. return self.items[index]
  28. end
  29. function Collection:deleteItem(index)
  30. table.remove(self.items,index)
  31. self:ondelete()
  32. end
  33. -- clears collection of anything
  34. function Collection:purge()
  35. for k,v in pairs(self.items) do self.items[k] = nil end
  36. end
  37. function Collection:getCount()
  38. return #self.items
  39. end
  40. function Collection:onadd() end
  41. function Collection:ondelete() end
  42. -- UIManager will try to update this collection, you should declare what should it do on every tick,
  43. --[[
  44. local collection = Collection:new("UColl")
  45. function collection:update(dt)
  46. .. do stuff
  47. end
  48. ]]
  49. -- otherwise it will do nothing
  50. UpdateableCollection = {}
  51. UpdateableCollection.__index = UpdateableCollection
  52. UpdateableCollection.ident = "ui_updateablecollection"
  53. UpdateableCollection.name = "UpdateableCollection"
  54. UpdateableCollection.updateable = true
  55. UpdateableCollection.input = false
  56. UpdateableCollection.drawable = false
  57. function UpdateableCollection:new(name)
  58. local self = {}
  59. setmetatable(self,UpdateableCollection)
  60. self.items = {}
  61. return self
  62. end
  63. setmetatable(UpdateableCollection,{__index = Collection})
  64. function UpdateableCollection:update(dt)
  65. local c = self:getCount()
  66. if c>0 then
  67. for i=1,c do
  68. self.items[i]:update(dt)
  69. end
  70. end
  71. end