Jump to content

Module:TwitterSnowflake/gen: Difference between revisions

From Humanipedia
mNo edit summary
 
update function
Line 1: Line 1:
<onlyinclude>{{#invoke:TwitterSnowflake/gen|getSnowflake}} {{#if: {{{update|}}}|<small>({{Purge|update}})</small>}}</onlyinclude>
local p = {}
{{documentation|content={{lua|Module:TwitterSnowflake/gen}}{{Module:TwitterSnowflake/gen/doc}}}}
 
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 timestampbinary = numberToBinStr(timestamp..math.random(0,9)..math.random(0,9)..math.random(0,9)) -- lua only provides time, so we append three random digits as "milliseconds"
local snowflakebinary = timestampbinary .. shard .. sequence
return string.format("%18.0f",tonumber(snowflakebinary,2))
end
 
return p

Revision as of 15:37, 20 January 2021

Usage

This generates a Snowflake ID of the current time, based off of Twitter's epoch.

Current ID: Template:TwitterSnowflake/gen

See also


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 timestampbinary = numberToBinStr(timestamp..math.random(0,9)..math.random(0,9)..math.random(0,9)) -- lua only provides time, so we append three random digits as "milliseconds"
	local snowflakebinary = timestampbinary .. shard .. sequence
	return string.format("%18.0f",tonumber(snowflakebinary,2))
end

return p