TurboTuTone

ComputerCraft UUID API

Jul 4th, 2013
691
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Lua 1.94 KB | None | 0 0
  1. -- UUID version 4 (random) API for ComputerCraft by TurboTuTone
  2. -- http://en.wikipedia.org/wiki/Universally_unique_identifier
  3. -- Format: xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx , where x is any hexadecimal digit and y is one of 8, 9, A, or B
  4. -- Partially based on: http://developer.coronalabs.com/code/uuidguid-string-generator-coronalua by FrankS
  5.  
  6. --  Generate, Generates UUID
  7. -- @returns string containing the uuid
  8. function Generate()
  9.     local chars = {"0","1","2","3","4","5","6","7","8","9","A","B","C","D","E","F"}
  10.     local uuid = {[9]="-",[14]="-",[15]="4",[19]="-",[24]="-"}
  11.     uuid[20] = chars[math.random (9,12)]
  12.     for i = 1,36 do
  13.         if(uuid[i]==nil)then
  14.             uuid[i] = chars[math.random (16)]
  15.         end
  16.     end
  17.     return table.concat(uuid)
  18. end
  19.  
  20. --  Validate, validates a uuid string.
  21. -- Params:
  22. -- @uuid = string containing the uuid.
  23. -- @notrim (optional) = if set to false, turns off trimming of leading and trailing whitespaces.
  24. -- @returns bool, true on validation, false if not valid.
  25. function Validate(uuid, notrim)
  26.     if not notrim == false or notrim == nil then
  27.         uuid = uuid:gsub("^%s*(.-)%s*$", "%1")
  28.     end
  29.     if #uuid==36 then
  30.         local fields = {}
  31.         local valid = { [1] = 8, [2] = 4, [3] = 4, [4] = 4, [5] = 12 }
  32.         uuid:gsub("([^%-]+)", function(a) fields[#fields+1] = a end)
  33.         for i=1,#valid do
  34.             if fields[i] == nil or #fields[i] ~= valid[i] then
  35.                 return false
  36.             end
  37.         end
  38.         if uuid:find("^[0-9ABCDEF]*%-[0-9ABCDEF]*%-4[0-9ABCDEF]*%-[89AB][0-9ABCDEF]*%-[0-9ABCDEF]*$") ~= nil then
  39.             return true
  40.         end
  41.     end
  42.     return false
  43. end
  44.  
  45. --  Compare, validates 2 uuid's then compares them for a match
  46. -- Params:
  47. -- @id1,id2 = uuid's to compare
  48. -- @notrim (optional) = if set to false, turns off trimming of leading and trailing whitespaces.
  49. -- @returns bool, true if uuid's match else false.
  50. function Compare(id1, id2, notrim)
  51.     if Validate(id1, notrim) and Validate(id2, notrim) then
  52.         if id1 == id2 then return true end
  53.     end
  54.     return false
  55. end
Advertisement
Add Comment
Please, Sign In to add comment