備忘録

備忘録

LuaでUUIDバージョン4を生成する方法

Ⅰ. はじめに

タイトルの通り「LuaでUUIDバージョン4を生成する方法」です。

Ⅱ. サンプルプログラム

math.randomseed(os.time())
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

-- テスト
for i = 1, 5 do
  myuuid = uuid()
  print(myuuid)
end

実行結果

794b1cd7-e8eb-468d-bf52-0d2287a54b9f
224d30ab-e3aa-4927-92d8-2aa521f86b25
d59b8a64-9ae3-430b-a391-53cb6dbf3619
463ffd53-7f1b-4326-b50e-b3a7a829c8b5
c19c1725-e269-4690-8f02-a4d1f6492d48