Skip to content

Instantly share code, notes, and snippets.

@eka
Last active March 21, 2024 02:40
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 eka/a383e46d948a82546334ca3d90a4c75f to your computer and use it in GitHub Desktop.
Save eka/a383e46d948a82546334ca3d90a4c75f to your computer and use it in GitHub Desktop.
Poormans UUID Generator for Godot 4.x
extends Node
func generate_uuid_v4() -> String:
var uuid = PackedByteArray()
for i in range(16):
uuid.append(randi() % 256)
# Set the version to 4 (randomly generated UUID)
uuid[6] = (uuid[6] & 0x0F) | 0x40
# Set the variant to DCE 1.1, ITU-T X.667
uuid[8] = (uuid[8] & 0x3F) | 0x80
# Convert to string format
var str_uuid = ""
for i in range(16):
str_uuid += "%02x" % uuid[i]
if i == 3 or i == 5 or i == 7 or i == 9:
str_uuid += "-"
return str_uuid
extends Node
# Assuming your UUID function is in a script named UUIDGenerator.gd
var uuid_generator = preload("res://uuid_generator.gd").new()
func _ready():
test_generate_uuid_v4_uniqueness(1000) # Test with 1000 UUIDs
func test_generate_uuid_v4_uniqueness(test_count: int):
var uuids = []
var duplicate_found = false
for i in range(test_count):
var uuid = uuid_generator.generate_uuid_v4()
if uuid in uuids:
print("Duplicate UUID Found: " + uuid)
duplicate_found = true
break
else:
uuids.append(uuid)
if not duplicate_found:
print("Test Passed: No duplicates found in " + str(test_count) + " generated UUIDs.")
else:
print("Test Failed: Duplicate UUID detected.")
# Optionally, you can also perform the format and version test on each generated UUID
test_uuid_format_and_version(uuids)
for uuid in uuids:
print(uuid)
func test_uuid_format_and_version(uuids):
var uuid_regex = RegEx.new()
uuid_regex.compile("^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-4[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}$")
for uuid in uuids:
if not uuid_regex.search(uuid):
print("Test Failed: UUID format or version incorrect - " + uuid)
return
print("All generated UUIDs have valid format and version.")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment