Created page with "local p = {} function p.uuid() math.randomseed(os.time() + tonumber(tostring({}):match("0x(.*)"), 16)) local template ='xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx' return string.gsub(template, '[xy]', function (c) local v = (c == 'x') and math.random(0, 0xf) or math.random(8, 0xb) return string.format('%x', v) end) end return p" |
No edit summary |
||
| Line 1: | Line 1: | ||
local p = {} | local p = {} | ||
-- Generate a random hex string of length n | |||
local function randhex(n) | |||
local s = "" | |||
for i = 1, n do | |||
s = s .. string.format("%x", math.random(0, 15)) | |||
end | |||
return s | |||
end | |||
function p.uuid() | function p.uuid() | ||
math.randomseed(os.time() + | -- Seed using time and a random factor | ||
math.randomseed(os.time() + math.random(1, 1000000)) | |||
-- UUID v4 format: xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx | |||
local uuid = string.format( | |||
"%s-%s-4%s-%s%s-%s", | |||
randhex(8), | |||
randhex(4), | |||
randhex(3), | |||
string.format("%x", math.random(8, 11)), | |||
randhex(2), | |||
randhex(12) | |||
) | |||
return uuid | |||
end | end | ||
return p | return p | ||
Latest revision as of 11:14, 20 March 2026
Documentation for this module may be created at Module:UUID/doc
local p = {}
-- Generate a random hex string of length n
local function randhex(n)
local s = ""
for i = 1, n do
s = s .. string.format("%x", math.random(0, 15))
end
return s
end
function p.uuid()
-- Seed using time and a random factor
math.randomseed(os.time() + math.random(1, 1000000))
-- UUID v4 format: xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx
local uuid = string.format(
"%s-%s-4%s-%s%s-%s",
randhex(8),
randhex(4),
randhex(3),
string.format("%x", math.random(8, 11)),
randhex(2),
randhex(12)
)
return uuid
end
return p