Created
July 29, 2012 09:26
-
-
Save jrus/3197011 to your computer and use it in GitHub Desktop.
quick lua implementation of "random" UUID
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
local random = math.random | |
local function uuid() | |
local template ='xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx' | |
return string.gsub(template, '[xy]', function (c) | |
local v = (c == 'x') and random(0, 0xf) or random(8, 0xb) | |
return string.format('%x', v) | |
end) | |
end |
@jrus Thank you for the snippet.
your can use this seed to avoid same uuid math.randomseed(tonumber(tostring(os.time()):reverse():sub(1, 9)))
I'd like to note, that this does not seem to work with lua 5.2.4. for i=1,10 do print(uuid()) end
will print 10 times the same UUID. However, without the custom seed, it works perfectly fine.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Alternate solution without an auxiliary table: replace in the top function
with
The first return value of
string.gsub
is assigned toans
, the others are ignored