Quick Links: Download Gideros Studio | Gideros Documentation | Gideros community chat | DONATE
UID generator — Gideros Forum

UID generator

antixantix Member
edited December 2015 in Code snippets
Hi all. Recently I needed a system to create UIDs' (Unique Identifiers) for my game objects, and this class is the result. It uses bits as opposed to integers, strings, bools, etc to store the information which saves a load of RAM (hopefully you can see the benefits of bitPools).

Call get() to get the next UID. The bitPool will expand as required so you can keep calling get() until you run out of RAM or exceed some LUA limitation.

By calling free(uid) you can release a UID to be re-issued by get()

Anyway, here is the code and I hope somebody finds it useful..
--
-- UID.lua - A simple UID (Unique Identifier) generator, by Antix Software 2015
--
 
UID = Core.class()
 
require "bit"
 
function UID:init()
  self.bitPool = {1} -- -- FIRST UID WILL ALWSYS BE 1
end
 
function UID:shutDown() -- EMPTY AND DESTROY BITPOOL
  for k in pairs (self.bitPool) do
    self.bitPool[k] = nil
  end
  self.bitPool = nil
end
 
function UID:get() -- GET NEXT UID
  for n = 1, #self.bitPool do
    for i = 0, 31 do
      if bit.band(self.bitPool[n], bit.rol(1, i)) == 0 then -- FIND FIRST FREE BIT
        self.bitPool[n] = self.bitPool[n] + bit.rol(1, i) -- SET BIT ALLOCATED
        return ((n - 1) * 32) + i -- RETURN UID
      end
    end
  end
  table.insert(self.bitPool, 1) -- BITPOOL IS FULL SO MAKE IT BIGGER
  return ((#self.bitPool - 1) * 32) -- RETURN UID
end
 
function UID:free(uid) -- RELEASE UID FOR RE-USE
  local b = math.fmod(uid, 32)
  local i = math.floor(uid / 32) + 1
  self.bitPool[i] = bit.band(self.bitPool[i], bit.rol(0xfffffffe, b)) -- CLEAR BIT
end
As always, any feedback on glaring bugs or optimizations are appreciated :)

Comments

Sign In or Register to comment.