Последняя активность 1 month ago

sparse_set.lua Исходник Playground
1local function push(self, thing)
2 -- Attempt to recycle a previously freed ID
3 local id = self.free_ids[#self.free_ids]
4 table.remove(self.free_ids)
5 if not id then
6 -- Othewise generate a new ID
7 id = self.next_id
8 self.next_id = self.next_id + 1
9 end
10 -- Assign the ID, the push the object into items
11 -- and add its position to indices.
12 thing.id = id
13 table.insert(self.items, thing)
14 self.indices[thing.id] = #self.items
15end
16
17local function pop(self, thing)
18 assert(self.indices[thing.id], "ID is not bound in this set")
19 assert(self.items[self.indices[thing.id]] == thing, "ID does not belong to this object")
20 -- Add the ID of this object to the free stack
21 table.insert(self.free_ids, thing.id)
22
23 -- Consume the current index
24 local index = self.indices[thing.id]
25 self.indices[thing.id] = nil
26
27 -- Swap and pop the last item in the set.
28 self.items[index] = self.items[#self.items]
29 table.remove(self.items)
30end
31
32local function each(self)
33 return ipairs(self.items)
34end
35
36local function sparse_set()
37 return { push = push, pop = pop, each = each, items = {}, indices = {}, free_ids = {}, next_id = 1 }
38end
39
40return sparse_set
41