Skip to content

Instantly share code, notes, and snippets.

@mathewmariani
Last active August 20, 2017 23:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mathewmariani/c36b9a49e26b0ffbb48dca0bb402cc72 to your computer and use it in GitHub Desktop.
Save mathewmariani/c36b9a49e26b0ffbb48dca0bb402cc72 to your computer and use it in GitHub Desktop.
Generates a random UUID string; version 4 as specified in RFC 4122.
function uuid4() {
local fn = function(c) {
local r = (((1.0 * rand() / RAND_MAX) * 16) + 1).tointeger();
local v = (c == "x") ? r : (r & 0x3 | 0x8);
return format("%x", r);
}
local string = "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx";
local expression = regexp(@"[xy]");
local captures = expression.capture(string);
local result = "";
local position = 0;
// thank you, m0pey
// http://www.squirrel-lang.org/forums/default.aspx?g=posts&m=6523
while (captures != null) {
foreach (i, capture in captures) {
result += string.slice(position, capture.begin);
result += fn(result);
position = capture.end;
}
captures = expression.capture(string, position);
}
result += string.slice(position);
return result;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment