Jump to content

Module:TwitterSnowflake/gen

From Wikipedia, the free encyclopedia
This is an old revision of this page, as edited by Elli (talk | contribs) at 02:49, 20 January 2021 (create module). The present address (URL) is a permanent link to this revision, which may differ significantly from the current revision.
(diff) ← Previous revision | Latest revision (diff) | Newer revision → (diff)

local p = {}

local function numberToBinStr(x)
	ret=""
	while x~=1 and x~=0 do
		ret=tostring(x%2)..ret
		x=math.modf(x/2)
	end
	ret=tostring(x)..ret
	return ret
end

function p.getSnowflake()
	local sequence = "000000000000" -- 12 sequence bits
	local shard = "0000000000" -- 10 shard bits
	local epoch = 1288834974
	local time = os.time()
	local timestamp = time - epoch
	local timestampms = timestamp * 1000 -- lua only provides time in seconds, grr
	local snowflakebinary = timestampms .. shard .. sequence
	return tonumber(snowflakebinary,2)
end

return p