Implementation of TypeID in Lua
1
2# TypeID in Lua
3
4https://luarocks.org/modules/pushcx/typeid
5
6This is an implementation of [TypeID](https://github.com/jetify-com/typeid) [0.3.0](https://github.com/jetify-com/typeid/tree/main/spec) in Lua.
7
8There's some C to get a timestamp in milliseconds, which is required to generate a [UUID7](https://en.wikipedia.org/wiki/Universally_unique_identifier#Version_7_\(timestamp_and_random\)).
9Lua's `os.time()` gives timestamps in seconds, presumably for maximum portability.
10Hopefully this is reasonably portable, but if not it's short enough to be reasonably replaced.
11
12**Maturity**: this was a toy project for me to practice Lua.
13It works and has good tests, including passing the TypeID suite.
14It's probably not idiomatic Lua.
15
16I've written up some notes on the implementation and alternatives in the [announcement blog post](https://push.cx/typeid-in-lua).
17
18
19# Use
20
21```lua
22TypeID = require("typeid")
23-- or in dev: TypeID = require("./typeid")
24
25t = TypeID.generate("comment")
26-- t = {
27-- prefix = "comment",
28-- suffix = "01jvbhbbdje07rnyqkvstpvcge"
29-- }
30
31-- TypeID tables implement __tostring
32print(t) -- "comment_01jvbhbbdje07rnyqkvstpvcge"
33
34-- You can extract a standard UUID string
35t:uuid() -- "0196d715-adb2-700f-8afa-f3de756db20e"
36
37-- and round trip that back into a TypeID
38TypeID.from_uuid_string("comment", "0196d715-adb2-700f-8afa-f3de756db20e")
39
40-- parse and validate a TypeID from a string
41TypeID.parse("comment_01jvbhbbdje07rnyqkvstpvcge")
42
43-- finally, you can generate with a unix timestamp in ms:
44TypeID.generate("comment", 1) -- "comment_0000000001e8avt0nh7a68v2jc"
45```
46
47
48# Build
49
50```
51# build and install
52$ luarocks make
53
54# build for development
55$ luarocks make --no-install
56```
57
58
59# Test
60
61```
62$ busted --shuffle
63●●●●●●●●●●●●●●●●●●●●●●●●●●●●●●●●●●●●●●●●●●●●
6447 successes / 0 failures / 0 errors / 0 pending : 0.019008 seconds
65```
66
67# Likely Issues
68
69 * The rockspec probably does not correctly depend on `sys/time.h`.
70 * I don't understand why `luarocks` generated the version `0.1-1`, what is the `-1` for?
71 Is my version `0.1` or `0.1-1`?
72 * The TypeID spec says "Implementations SHOULD allow encoding/decoding of other UUID variants" but does not mandate validating them, so I don't.
73 Perhaps the spec should say implementations should not permit any old 128 bits.