Skip to content

Instantly share code, notes, and snippets.

@RyanPattison
RyanPattison / alias_table.lua
Last active March 31, 2024 00:31
A Lua implementation of the Alias Method, for sampling from an arbitrary distribution.
local alias_table = {}
function alias_table:new(weights)
local total = 0
for _,v in ipairs(weights) do
assert(v >= 0, "all weights must be non-negative")
total = total + v
end
assert(total > 0, "total weight must be positive")
@RyanPattison
RyanPattison / ordered_table.lua
Last active January 29, 2023 16:01
Ordered table for Lua. A table that keeps track of the order that keys are added and makes pairs iterate in order of insertion. Also, it maintains/reports the correct number of items in the table with the `#` operator.
local ordered_table = {}
--[[
This implementation of ordered table does not hold performance above functionality.
It invokes a metamethod `__newindex` for every access, and
while this is not ideal performance wise, the resulting table behaves very closely to
a standard Lua table, with the quirk that the keys are ordered by when they are first seen
(unless deleted and then reinserted.)
--]]
-- private unique keys