-
-
Save jrus/3197011 to your computer and use it in GitHub Desktop.
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 |
And there it is! FTR, and as stated here, as soon as I wrapped all the string.gsub part into parenthesis, only the UUID is returned by the main function an everything seems to work as expected, cool! Thankfully, in Lua the simple addition of some parenthesis here or there is usually enough to save the day :)
You can try this:
return {string.format('%x', v)}[1]
You just wrap it into a table and then index the first object in that table.
Alternate solution without an auxiliary table: replace in the top function
return string.gsub(...)
with
local ans = string.gsub(...)
return ans
The first return value of string.gsub
is assigned to ans
, the others are ignored
@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.
And there it is! FTR, and as stated here, as soon as I wrapped all the string.gsub part into parenthesis, only the UUID is returned by the main function an everything seems to work as expected, cool! Thankfully, in Lua the simple addition of some parenthesis here or there is usually enough to save the day :)