Module ulid

Module for creating Universally Unique Lexicographically Sortable Identifiers.

Modeled after the ulid implementation by alizain. Please checkout the documentation there for the design and characteristics of ulid.

IMPORTANT: the standard Lua versions, based on the standard C library are unfortunately very weak regarding time functions and randomizers. So make sure to set it up properly!

Info:

  • Copyright: Copyright 2016-2017 Thijs Schreijer
  • License: mit
  • Author: Thijs Schreijer

Functions

set_time_func (f) Sets the time function to get default times from.
set_random_func (f) Sets the random function to get random input from.
encode_time (time, len) generates the time-based part of a ulid.
encode_random (len) generates the random part of a ulid.
ulid (time) generates a ulid.


Functions

set_time_func (f)
Sets the time function to get default times from. This function should return time in seconds since unix epoch, with millisecond precision. The default set will be ngx.now() or alternatively socket.gettime(), if niether is available, it will insert an error throwing placeholder function.

Parameters:

  • f the function to set

Returns:

    true
set_random_func (f)
Sets the random function to get random input from. This function should return a number between 0 and 1 when called without arguments. The default is math.random, this is ok for LuaJIT, but the standard PuC-Rio Lua versions have a weak randomizer that is better replaced.

Parameters:

  • f the function to set

Returns:

    true
encode_time (time, len)
generates the time-based part of a ulid.

Parameters:

  • time (optional) time to generate the string from, in seconds since unix epoch, with millisecond precision (defaults to now)
  • len (optional) the length of the time-based string to return (defaults to 10)

Returns:

    time-based part of ulid string
encode_random (len)
generates the random part of a ulid.

Parameters:

  • len (optional) the length of the random string to return (defaults to 16)

Returns:

    random part of ulid string
ulid (time)
generates a ulid.

Parameters:

  • time (optional) time to generate the ulid from, in seconds since unix epoch, with millisecond precision (defaults to now)

Returns:

    ulid string

Usage:

    local ulid_mod = require("ulid")
    
    -- load LuaSocket so we can reuse its gettime function
    local socket = require("socket")
    -- set the time function explicitly, but by default it
    -- will be picked up as well
    ulid_mod.set_time_func(socket.gettime)
    
    -- seed the random generator, needed for the example, but ONLY DO THIS ONCE in your
    -- application, unless you know what you are doing! And try to use a better seed than
    -- the time based seed used here.
    math.randomseed(socket.gettime()*10000)
    
    -- get a ulid from current time
    local id = ulid_mod.ulid()
generated by LDoc 1.4.6 Last updated 2017-03-28 14:40:33