In Neovim, Random Ain't Random

I recently discovered that Neovim doesn’t pre-seed Lua’s math.random by default.

This caused issues in my editor for displaying a fortune from alpha-nvim’s fortune module. Alpha nvim defines a bunch of hardcoded fortunes in a list and then uses math.random to pick which fortune to use. Unfortunately, on start up this resulted in me seeing the same fortune over and over.

To resolve this, I had to non-deterministically seed Lua’s pseudo-random generator via math.randomseed.

My fix was to place the following at the very top of my init.lua in my Neovim configuration:

math.randomseed(vim.uv.hrtime())

vim.uv.hrtime is the current time in nanoseconds — pretty much ensuring that multiple sessions of Neovim get different seeds even if they’re launched at effectively the same time.