diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml new file mode 100644 index 0000000..2b32853 --- /dev/null +++ b/.github/workflows/test.yml @@ -0,0 +1,32 @@ +name: test + +on: + push: + pull_request: + +jobs: + busted: + name: busted (Lua ${{ matrix.lua }}) + runs-on: ubuntu-latest + strategy: + fail-fast: false + matrix: + lua: ["5.1", "5.2", "5.3", "5.4", "luajit-2.1"] + + steps: + - uses: actions/checkout@v5 + + - uses: leafo/gh-actions-lua@v13 + with: + luaVersion: ${{ matrix.lua }} + + # LuaRocks < 3.12 can't load the luarocks.org manifest on LuaJIT; v6 installs 3.13 + - uses: leafo/gh-actions-luarocks@v6 + + - name: Install busted + run: luarocks install busted + + - name: Run the test suite + run: | + lua -v + busted --exclude-tags=knownbug diff --git a/README.md b/README.md index e19357a..fe70288 100644 --- a/README.md +++ b/README.md @@ -1,13 +1,20 @@

lua-table

-# Lua-Table 0.7 +# Lua-Table 0.8.0 +[![test](https://github.com/Luca96/lua-table/actions/workflows/test.yml/badge.svg)](https://github.com/Luca96/lua-table/actions/workflows/test.yml) + Lua tables with superpowers :muscle: +Supports Lua 5.1, 5.2, 5.3, 5.4 and LuaJIT 2.1. + ## Changes View the ```changelog``` for more info about changes. ## Installation -To install the library just ```clone``` the repo or install via [LuaRocks](https://luarocks.org/modules/Luca96/luatable). +To install the library just ```clone``` the repo or install via [LuaRocks](https://luarocks.org/modules/Luca96/luatable): +``` +luarocks install luatable +``` ## Running tests The test suite lives in `spec/` and uses [busted](https://lunarmodules.github.io/busted/): @@ -15,6 +22,10 @@ The test suite lives in `spec/` and uses [busted](https://lunarmodules.github.io luarocks install busted busted ``` +or, through LuaRocks (installs busted first if it is missing): +``` +luarocks test +``` ## Examples ```lua @@ -27,9 +38,15 @@ local t = { 1, 2, 2, 3, -4, 5 } -- remove negative values t = table.accept(t, table.positive) --- create an enhanched table from an old one +-- create an enhanched table from an old one (t itself gains the methods, no copy) local tb = table(t) +-- table.of always packs its arguments: a single table becomes the only element +local nested = table.of(t) --> { t } + +-- a table init value is deep-copied into each slot +local grid = table.init(3, { 0, 0 }) + -- print every element tb:eachi(print) @@ -54,6 +71,11 @@ local t2 = { 1, 2, 3, 4, 5 } print(table.equal(t1, t2)) --> false print(table.equal(t1, t2, true)) --> true +-- deep equality (and deepflat) visit hash keys in a fixed order, not pairs order: +-- numbers, strings, booleans, then tables (compared by content), then functions, +-- userdata and threads (by identity, so these keys only line up when both tables +-- use the same key objects) + -- operator overloads local t1 = table { 1, 2, 3 } local t2 = table { 2, 4, 5 } @@ -73,13 +95,6 @@ This section tracks what is still open. Update it when an item is fixed or a new - **Dot-access returns library functions.** Enhanced tables use `__index = table`, so `tb.sum` or `tb.map` on a table without those keys returns the library function instead of `nil`. `get` and `haskey` are not affected; plain indexing is. -- **Deep equality depends on `pairs` order.** `equal(a, b, true)` compares hash-part values in - `pairs` order, so two tables with the same content can compare unequal. -- **`table.new(t)` wraps in place.** A single table argument is turned into the enhanced table - itself (no copy), so `table.new({x})` can't create a one-element table that holds `{x}`. -- **`init(n, {})` shares one table.** A table init value is stored by reference in every slot. -- **`shuffle` is biased.** It swaps each slot with a random slot from the whole table, so some - orderings are more likely than others; it should use Fisher-Yates. ### Roadmap - **Module instead of global extension.** Today the library adds its functions to Lua's global @@ -87,6 +102,4 @@ This section tracks what is still open. Update it when an item is fixed or a new `__index = table` as a fallback, so `local table = require "luatable"` works as now while the global `table` stays untouched, plus an optional `luatable.install()` for the current global behaviour. This avoids name clashes with future Lua versions or other libraries. -- CI running busted on Lua 5.1, 5.4 and LuaJIT. -- A `test` section in the rockspec, so `luarocks test` runs the suite. -- Version bump and release once the fixes in the changelog's *Unreleased* section ship. +- Upload the 0.8.0 rockspec to LuaRocks (tag `v0.8.0` first). diff --git a/changelog.md b/changelog.md index 0cf2828..21fb907 100644 --- a/changelog.md +++ b/changelog.md @@ -1,6 +1,12 @@ # Lua-Table Changelog ## Unreleased + +## (0.8.0) 20/11/2026: +- first stable LuaRocks release (only the scm rock was published before): `luarocks install luatable` +- CI: GitHub Actions runs busted on Lua 5.1, 5.2, 5.3, 5.4 and LuaJIT 2.1 +- rockspec: requires `lua >= 5.1`; package name is lowercase `luatable` +- table.info() reports version 0.8.0 - added a busted unit test suite (`spec/`) - fixed group, slide, lshift, rshift and shift on Lua 5.2+ (`unpack` is now `table.unpack`) - slide now yields only full windows @@ -17,6 +23,15 @@ ancestor, tostring renders them as ``, clone and purify reproduce the cycle in the copy - clone now keeps shared references shared in the copy (each occurrence used to get its own copy) - argument errors now report the caller's file and line instead of a line inside luatable.lua +- rockspec: added a busted test section (`luarocks test`) and fixed the source URL (git+https) +- deepflat visits hash keys in a fixed order (numbers, strings, booleans, tables by content, + then other types), so its output and deep equal (`equal(a, b, true)`) no longer depend on + `pairs` order +- added table.of(...): always packs its arguments, so `table.of(t)` is `{ t }` (table.new and + `table(t)` still wrap a single table in place) +- init deep-copies a table init value into each slot instead of sharing one table (behaviour + change; copies are enhanced tables) +- shuffle is now uniform (Fisher-Yates); every ordering used to have a different probability ## (0.7) 16/07/2018: - code rewriting: now the library extends the global table object diff --git a/rockspecs/luatable-0.8.0-1.rockspec b/rockspecs/luatable-0.8.0-1.rockspec new file mode 100644 index 0000000..800b643 --- /dev/null +++ b/rockspecs/luatable-0.8.0-1.rockspec @@ -0,0 +1,42 @@ +rockspec_format = "3.0" +package = "luatable" +version = "0.8.0-1" + +source = { + url = "git+https://github.com/Luca96/lua-table.git", + tag = "v0.8.0", +} + +description = { + summary = "A library that gives superpowers to Lua tables", + detailed = [[ + Extends Lua's table library with iterators (range, group, slide, keys, values, + inverse), functional helpers (map, reduce, accept, reject, flat, deepflat, flatmap, + all, any), set operations (union, negation, intersect, unique, keySet, valueSet), + utilities (max, min, avg, sample, shuffle, reverse, slice, find, clone, merge, + purify, equal) and enhanced tables with methods and operator overloads + (+ - * .. ==). Works on Lua 5.1 - 5.4 and LuaJIT 2.1. + ]], + homepage = "https://github.com/Luca96/lua-table", + license = "MIT", + labels = { "datastructure", "utility", "functional" }, +} + +dependencies = { + "lua >= 5.1", +} + +test_dependencies = { + "busted", +} + +test = { + type = "busted", +} + +build = { + type = "builtin", + modules = { + luatable = "src/luatable.lua", + }, +} diff --git a/rockspecs/luatable-scm-1.rockspec b/rockspecs/luatable-scm-1.rockspec index 5790268..d4e55a6 100644 --- a/rockspecs/luatable-scm-1.rockspec +++ b/rockspecs/luatable-scm-1.rockspec @@ -1,8 +1,9 @@ -package = "LuaTable" +rockspec_format = "3.0" +package = "luatable" version = "scm-1" source = { - url = "git://github.com/Luca96/lua-table", + url = "git+https://github.com/Luca96/lua-table.git", } description = { @@ -16,7 +17,15 @@ description = { } dependencies = { - "lua" + "lua >= 5.1" +} + +test_dependencies = { + "busted", +} + +test = { + type = "busted", } build = { diff --git a/spec/constructors_spec.lua b/spec/constructors_spec.lua index 35329ff..768f58a 100644 --- a/spec/constructors_spec.lua +++ b/spec/constructors_spec.lua @@ -34,6 +34,32 @@ describe("constructors", function() end) end) + describe("table.of", function() + it("creates an empty enhanced table with no arguments", function() + local t = T.of() + assert.is_true(is_enhanced(t)) + assert.are.same({}, plain(t)) + end) + + it("packs its arguments", function() + assert.are.same({ 1, 2, 3 }, plain(T.of(1, 2, 3))) + end) + + it("keeps a single table argument as the only element", function() + local x = { 1, 2 } + local t = T.of(x) + assert.are.equal(1, #t) + assert.is_true(rawequal(x, t[1])) + assert.is_true(is_enhanced(t)) + end) + + it("leaves the argument's metatable alone", function() + local x = { 1 } + T.of(x) + assert.is_nil(getmetatable(x)) + end) + end) + describe("calling the library", function() it("table{...} is the same as table.new{...}", function() local t = T { 4, 5 } @@ -60,9 +86,25 @@ describe("constructors", function() assert.are.same({ 10, 20, 30 }, plain(t)) end) - it("shares one reference when the init value is a table", function() - local t = T.init(2, {}) - assert.is_true(rawequal(t[1], t[2])) + it("gives every slot its own deep copy of a table init value", function() + local def = { 0, inner = { 1 } } + local t = T.init(2, def) + assert.is_false(rawequal(t[1], t[2])) + assert.is_false(rawequal(t[1], def)) + assert.is_false(rawequal(t[1].inner, t[2].inner)) + assert.is_false(rawequal(t[1].inner, def.inner)) + assert.are.same({ { 0, inner = { 1 } }, { 0, inner = { 1 } } }, plain(t)) + end) + + it("slots stay independent when one is changed", function() + local t = T.init(2, { 0 }) + t[1][1] = 9 + assert.are.same({ { 9 }, { 0 } }, plain(t)) + end) + + it("copies of a table init value are enhanced tables", function() + local t = T.init(1, {}) + assert.is_true(is_enhanced(t[1])) end) it("returns an empty enhanced table for size 0", function() diff --git a/spec/functional_spec.lua b/spec/functional_spec.lua index ad4b682..f58c15d 100644 --- a/spec/functional_spec.lua +++ b/spec/functional_spec.lua @@ -122,6 +122,61 @@ describe("functional utils", function() t.x = t assert.are.same({ 1 }, plain(T.deepflat(t))) end) + + it("visits hash keys in sorted order, after the array part", function() + assert.are.same({ 3, 1, 2 }, plain(T.deepflat({ 3, b = 2, a = 1 }))) + -- regression: with 10 keys, pairs order is practically never sorted + local t = { c = 3, h = 8, a = 1, j = 10, e = 5, b = 2, g = 7, d = 4, i = 9, f = 6 } + assert.are.same({ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }, plain(T.deepflat(t))) + end) + + it("ranks key types: numbers, strings, booleans, tables, then the rest", function() + local f = function() end + local t = { [f] = "func", [{}] = "table", [true] = "true", [false] = "false", + s = "string", [2.5] = "number", [-1] = "negative" } + assert.are.same({ "negative", "number", "string", "false", "true", "table", "func" }, + plain(T.deepflat(t))) + end) + + it("orders table keys by their content", function() + assert.are.same({ "a", "b" }, plain(T.deepflat({ [{ 2 }] = "b", [{ 1 }] = "a" }))) + -- the first difference decides; a shorter prefix comes first + local t = { [{ 1, 2, 9 }] = "c", [{ 1, 2 }] = "a", [{ 1, 2, 3 }] = "b", [{ 0, 99 }] = "z" } + assert.are.same({ "z", "a", "b", "c" }, plain(T.deepflat(t))) + -- key content is flattened with the same rules (nested, hash keys sorted) + t = { [{ y = 2, x = 1 }] = "b", [{ { 1 }, 1 }] = "a" } + assert.are.same({ "a", "b" }, plain(T.deepflat(t))) + end) + + it("orders keys with the same content by their value", function() + local t = { [{ 1 }] = "b", [{ 1 }] = "a", [{ 1 }] = "c" } + assert.are.same({ "a", "b", "c" }, plain(T.deepflat(t))) + end) + + it("terminates when a key table refers back to the table", function() + local t = { 1 } + local k = { 2 } + k[2] = t + k[3] = k + t[k] = 3 + t[{ 0 }] = 4 + assert.are.same({ 1, 4, 3 }, plain(T.deepflat(t))) + end) + + it("terminates when the table is a key of itself (empty content, sorts first)", function() + local t = { 1 } + t[t] = 2 + t[{ 0 }] = 3 + assert.are.same({ 1, 2, 3 }, plain(T.deepflat(t))) + end) + + it("handles NaN values under equal-content keys", function() + local nan = 0 / 0 + local r = T.deepflat({ [{ 1 }] = nan, [{ 1 }] = 2, [{ 1 }] = nan }) + assert.are.equal(3, #r) + assert.are.equal(2, r[1]) + assert.is_true(r[2] ~= r[2] and r[3] ~= r[3]) + end) end) describe("table.flatmap", function() diff --git a/spec/helpers.lua b/spec/helpers.lua index 3cf5a28..61c6302 100644 --- a/spec/helpers.lua +++ b/spec/helpers.lua @@ -73,6 +73,72 @@ function helpers.fn(s) return function(...) return s(...) end end +-- Keys of t in `pairs` order, as one string (to compare iteration orders). +local function key_order(t) + local keys = {} + + for k in next, t do + keys[#keys + 1] = tostring(k) + end + + return table.concat(keys, ",") +end + +-- Copy of t (keys in the given order) inside a hash part grown by n placeholder keys. +-- The placeholders are removed afterwards: deleting keys never shrinks a table, so the +-- copy keeps the bigger hash part. (A constructor with nil fields would presize on +-- PUC Lua but not on LuaJIT.) +local function copy_presized(t, keys, n) + local copy, placeholders = {}, {} + + for i = 1, n do + placeholders[i] = {} + copy[placeholders[i]] = true + end + + for i = 1, #keys do + copy[keys[i]] = t[keys[i]] + end + + for i = 1, n do + copy[placeholders[i]] = nil + end + + return copy +end + +-- Shallow copy of t with the same content but a different `pairs` order. A key's slot +-- depends on the hash-part size (and on insertion order when keys collide), so this +-- tries growing hash parts, inserting forwards and backwards, until the order +-- differs. Fails if none does (use several varied keys so that is practically impossible). +function helpers.reordered(t) + local keys = {} + + for k in next, t do + keys[#keys + 1] = k + end + + local want = key_order(t) + + local backwards_keys = {} + + for i = 1, #keys do + backwards_keys[i] = keys[#keys - i + 1] + end + + for size = 0, 10 do + for _, order in ipairs({ backwards_keys, keys }) do + local copy = copy_presized(t, order, 2 ^ size) + + if key_order(copy) ~= want then + return copy + end + end + end + + error("reordered(): could not change the pairs order", 2) +end + -- Plain, sorted copy of a list; for results that follow the unspecified `pairs` order. function helpers.sorted(list) local copy = {} diff --git a/spec/regression.lua b/spec/regression.lua new file mode 100644 index 0000000..7daea09 --- /dev/null +++ b/spec/regression.lua @@ -0,0 +1,408 @@ +----------------------------------------------------------------------------------------- +-- lua-table end-to-end regression script (internal; busted only runs *_spec files) +-- +-- Exercises every public function of the library, prints what each call returns and +-- checks it against the expected value. Needs only plain `lua`, no busted. Run it from +-- anywhere: +-- +-- lua spec/regression.lua +-- +-- Each line shows "ok" or "FAIL"; the script exits with status 1 if anything failed. +----------------------------------------------------------------------------------------- + +-- load the library from ../src relative to this file, so the script runs from any folder +local here = debug.getinfo(1, "S").source:match("^@(.*[/\\])") or "./" +package.path = here .. "../src/?.lua;" .. package.path + +local table = require "luatable" -- the extended table library (README style) + +----------------------------------------------------------------------------------------- +-- tiny helpers: render values, compare them, report results +----------------------------------------------------------------------------------------- +local passed, failed = 0, 0 + +-- compact, deterministic rendering: array part first, then other keys sorted by name. +-- uses rawget/next so enhanced-table metamethods never interfere; cycles show as +local function show(v, seen) + if type(v) == "string" then return ("%q"):format(v) end + if type(v) ~= "table" then return tostring(v) end + + seen = seen or {} + if seen[v] then return "" end + seen[v] = true + + local parts, n = {}, #v + + for i = 1, n do + parts[#parts + 1] = show(rawget(v, i), seen) + end + + local keys = {} + for k in next, v do + local in_array = type(k) == "number" and k >= 1 and k <= n and k % 1 == 0 + if not in_array then keys[#keys + 1] = k end + end + table.sort(keys, function(a, b) return tostring(a) < tostring(b) end) + + for _, k in ipairs(keys) do + local name = (type(k) == "string" and k:match("^[%a_][%w_]*$")) and k or "[" .. show(k, seen) .. "]" + parts[#parts + 1] = name .. " = " .. show(rawget(v, k), seen) + end + + seen[v] = nil + return "{" .. table.concat(parts, ", ") .. "}" +end + +-- structural equality that ignores metatables (enhanced tables overload ==) +local function same(a, b, seen) + if rawequal(a, b) then return true end + if type(a) ~= "table" or type(b) ~= "table" then return a == b end + + seen = seen or {} + if seen[a] == b then return true end + seen[a] = b + + for k, v in next, a do + if not same(v, rawget(b, k), seen) then return false end + end + for k in next, b do + if rawget(a, k) == nil then return false end + end + return true +end + +local function check(label, got, expected) + if same(got, expected) then + passed = passed + 1 + print((" ok %-44s %s"):format(label, show(got))) + else + failed = failed + 1 + print((" FAIL %-44s got %s, expected %s"):format(label, show(got), show(expected))) + end +end + +local function section(title) + print("\n== " .. title .. " " .. ("="):rep(math.max(0, 70 - #title))) +end + +-- drain an iterator: one value per step, or a list when it yields `arity` values +local function collect(iter, arity) + local out = {} + while true do + local step = { iter() } + if step[1] == nil then return out end + out[#out + 1] = (arity or 1) == 1 and step[1] or step + end +end + +-- sorted copy, for results that follow the (unspecified) pairs order +local function sorted(list) + local copy = {} + for i = 1, #list do copy[i] = list[i] end + table.sort(copy, function(a, b) return tostring(a) < tostring(b) end) + return copy +end + +-- same content as t, but a different pairs order: a key's slot depends on the size of +-- the hash part, so copy t into tables grown by n placeholder keys (removed afterwards: +-- deleting keys never shrinks a table) until the iteration order changes +local function reordered(t) + local function order(x) + local keys = {} + for k in next, x do keys[#keys + 1] = tostring(k) end + return table.concat(keys, ",") + end + + for size = 0, 10 do + local copy, placeholders = {}, {} + for i = 1, 2 ^ size do placeholders[i] = {}; copy[placeholders[i]] = true end + for k, v in next, t do copy[k] = v end + for i = 1, #placeholders do copy[placeholders[i]] = nil end + if order(copy) ~= order(t) then return copy end + end + + error("reordered(): could not change the pairs order") +end + +local function strip_ansi(s) + return (tostring(s):gsub("\27%[[%d;]*m", "")) +end + +----------------------------------------------------------------------------------------- +section("library info") +----------------------------------------------------------------------------------------- +table.info() +do -- info() prints through a cached print, so read its version from the source + local f = assert(io.open(here .. "../src/luatable.lua", "rb")) + local version = f:read("*a"):match("function table%.info%(%).-version: ([%d.]+)") + f:close() + check("info() reports version 0.8.0", version, "0.8.0") + local spec = io.open(here .. "../rockspecs/luatable-" .. tostring(version) .. "-1.rockspec", "rb") + check(" ...with a matching release rockspec", spec ~= nil, true) + if spec then spec:close() end +end + +----------------------------------------------------------------------------------------- +section("constructors") +----------------------------------------------------------------------------------------- +check("table.new(1, 2, 3)", table.new(1, 2, 3), { 1, 2, 3 }) +check("table { 4, 5 } (call syntax)", table { 4, 5 }, { 4, 5 }) +check("table(\"a\", \"b\")", table("a", "b"), { "a", "b" }) + +local plain = { 7, 8 } +local wrapped = table.new(plain) +check("table.new(t) wraps t in place", rawequal(wrapped, plain), true) +check("...and t gains methods", plain:last(), 8) + +local box = { 7 } +check("table.of(t) holds t as an element", { #table.of(box), rawequal(table.of(box)[1], box) }, { 1, true }) +check("...leaving t without methods", getmetatable(box), nil) +check("table.of(1, 2, 3)", table.of(1, 2, 3), { 1, 2, 3 }) + +check("table.init(3, \"x\")", table.init(3, "x"), { "x", "x", "x" }) +check("table.init(4, i -> i*i)", table.init(4, function(i) return i * i end), { 1, 4, 9, 16 }) +check("table.init(3, f, 10) (extra args)", table.init(3, function(i, base) return base + i end, 10), { 11, 12, 13 }) + +local grid = table.init(2, { 0 }) +grid[1][1] = 9 +check("table.init(2, {0}) (a copy per slot)", grid, { { 9 }, { 0 } }) +check("table.zeros(3)", table.zeros(3), { 0, 0, 0 }) +check("table.ones(2)", table.ones(2), { 1, 1 }) +check("table.ofChars(\"lua\")", table.ofChars("lua"), { "l", "u", "a" }) + +----------------------------------------------------------------------------------------- +section("small operator functions (for map / reduce / accept ...)") +----------------------------------------------------------------------------------------- +check("odd(3), even(3)", { table.odd(3), table.even(3) }, { true, false }) +check("half(5), double(4)", { table.half(5), table.double(4) }, { 2.5, 8 }) +check("sqr(3), pow(2, 8)", { table.sqr(3), table.pow(2, 8) }, { 9, 256 }) +check("increase(1), decrease(1)", { table.increase(1), table.decrease(1) }, { 2, 0 }) +check("positive(-1), negative(-1)", { table.positive(-1), table.negative(-1) }, { false, true }) +check("itself(\"x\"), identity(1)", { table.itself("x"), table.identity(1) }, { "x", true }) +check("isnil(nil), isnil(false)", { table.isnil(nil), table.isnil(false) }, { true, false }) +check("eq, neq, gt, lt, ge, le", + { table.eq(1, 1), table.neq(1, 1), table.gt(2, 1), table.lt(2, 1), table.ge(1, 1), table.le(2, 1) }, + { true, false, true, false, true, false }) +check("sum, sub, mul, div", + { table.sum(2, 3), table.sub(5, 3), table.mul(2, 3), table.div(7, 2) }, + { 5, 2, 6, 3.5 }) +check("void() returns nothing", select("#", table.void()), 0) + +----------------------------------------------------------------------------------------- +section("functional utils") +----------------------------------------------------------------------------------------- +check("map({1,2,3}, double)", table.map({ 1, 2, 3 }, table.double), { 2, 4, 6 }) +check("map({1,2,3}, pow, 2) (extra args)", table.map({ 1, 2, 3 }, table.pow, 2), { 1, 4, 9 }) +check("reduce({1,2,3,4}, 0, sum)", table.reduce({ 1, 2, 3, 4 }, 0, table.sum), 10) +check("reduce({1,2,3,4}, 1, mul)", table.reduce({ 1, 2, 3, 4 }, 1, table.mul), 24) +check("accept({1,-2,3,-4}, positive)", table.accept({ 1, -2, 3, -4 }, table.positive), { 1, 3 }) +check("reject({1,-2,3,-4}, positive)", table.reject({ 1, -2, 3, -4 }, table.positive), { -2, -4 }) +check("accept({1,2,3}, gt, 1)", table.accept({ 1, 2, 3 }, table.gt, 1), { 2, 3 }) +check("flat({1, {2, {3, 4}}, 5})", table.flat({ 1, { 2, { 3, 4 } }, 5 }), { 1, 2, 3, 4, 5 }) +check("flat ignores hash keys", table.flat({ 1, x = { 2 } }), { 1 }) +check("deepflat({1, {2}, x = {3}})", table.deepflat({ 1, { 2 }, x = { 3 } }), { 1, 2, 3 }) +check("deepflat({3, b = 2, a = 1}) (sorted)", table.deepflat({ 3, b = 2, a = 1 }), { 3, 1, 2 }) +check("deepflat(10 keys) (sorted, not pairs)", + table.deepflat({ c = 3, h = 8, a = 1, j = 10, e = 5, b = 2, g = 7, d = 4, i = 9, f = 6 }), + { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }) +check("deepflat({[{2}]=\"b\", [{1}]=\"a\"}) (by key content)", + table.deepflat({ [{ 2 }] = "b", [{ 1 }] = "a" }), { "a", "b" }) +check("flatmap({1,2}, v -> {v, v*10})", + table.flatmap({ 1, 2 }, function(v) return { v, v * 10 } end), { 1, 10, 2, 20 }) +check("all({2,4}, even), all({2,3}, even)", { table.all({ 2, 4 }, table.even), table.all({ 2, 3 }, table.even) }, { true, false }) +check("any({1,2}, even), any({1,3}, even)", { table.any({ 1, 2 }, table.even), table.any({ 1, 3 }, table.even) }, { true, false }) +check("allPairs / anyPairs see hash values", + { table.allPairs({ 2, x = 3 }, table.even), table.anyPairs({ 1, x = 2 }, table.even) }, { false, true }) + +-- method chaining on an enhanced table +check("table{1,2,3,4}:accept(even):map(sqr):reduce(0, sum)", + table { 1, 2, 3, 4 }:accept(table.even):map(table.sqr):reduce(0, table.sum), 20) + +----------------------------------------------------------------------------------------- +section("iterators") +----------------------------------------------------------------------------------------- +local letters = { "a", "b", "c", "d" } + +local seen_in_loop = {} +for v in table.iter(letters) do seen_in_loop[#seen_in_loop + 1] = v end -- plain for-in loop +check("for v in iter(t)", seen_in_loop, { "a", "b", "c", "d" }) +check("inverse(t)", collect(table.inverse(letters)), { "d", "c", "b", "a" }) +check("range(t)", collect(table.range(letters), 2), + { { 1, "a" }, { 2, "b" }, { 3, "c" }, { 4, "d" } }) +check("range(t, 3) (from index 3)", collect(table.range(letters, 3), 2), { { 3, "c" }, { 4, "d" } }) +check("range(t, 1, 2, 2) (count 2, step 2)", collect(table.range(letters, 1, 2, 2), 2), { { 1, "a" }, { 3, "c" } }) +check("range(t, 4, nil, -1) (backwards)", collect(table.range(letters, 4, nil, -1), 2), + { { 4, "d" }, { 3, "c" }, { 2, "b" }, { 1, "a" } }) +check("group({1..5}, 2)", collect(table.group({ 1, 2, 3, 4, 5 }, 2), 2), { { 1, 2 }, { 3, 4 }, { 5 } }) +check("slide({1..4}, 3) (full windows)", collect(table.slide({ 1, 2, 3, 4 }, 3), 3), { { 1, 2, 3 }, { 2, 3, 4 } }) +check("keys({10, 20, x = 30})", sorted(collect(table.keys({ 10, 20, x = 30 }))), { 1, 2, "x" }) +check("values({10, 20, x = 30})", sorted(collect(table.values({ 10, 20, x = 30 }))), { 10, 20, 30 }) + +local visited = {} +table.eachi({ "a", "b" }, function(v, suffix) visited[#visited + 1] = v .. suffix end, "!") +check("eachi(t, f, \"!\")", visited, { "a!", "b!" }) + +visited = {} +table.each({ 1, x = 2 }, function(k, v) visited[#visited + 1] = tostring(k) .. "=" .. v end) +check("each(t, f) (all key/value pairs)", sorted(visited), { "1=1", "x=2" }) + +----------------------------------------------------------------------------------------- +section("utility") +----------------------------------------------------------------------------------------- +check("purify({[1]=\"a\", [5]=\"b\", [9]=\"c\", x=1})", + table.purify({ [1] = "a", [5] = "b", [9] = "c", x = 1 }), { "a", "b", "c", x = 1 }) +check("max({3, 7, 2}), min({3, 7, 2})", { table.max({ 3, 7, 2 }), table.min({ 3, 7, 2 }) }, { 7, 2 }) +check("max(words, longer-than)", + table.max({ "aa", "b", "cccc" }, function(a, b) return #a > #b end), "cccc") +check("avg({2, 4, 6})", table.avg({ 2, 4, 6 }), 4) +check("maximize({-5, 1, 3}, sqr)", table.maximize({ -5, 1, 3 }, table.sqr), -5) +check("minimize({-5, 1, 3}, sqr)", table.minimize({ -5, 1, 3 }, table.sqr), 1) + +math.randomseed(42) +local pool = { "x", "y", "z" } +check("sample(t) is an element of t", table.find(pool, table.sample(pool)) ~= nil, true) +local deck = { 1, 2, 3, 4, 5, 6 } +table.shuffle(deck) +print(" shuffle({1..6}) -> " .. show(deck)) +check("shuffle keeps the same elements", sorted(deck), { 1, 2, 3, 4, 5, 6 }) + +-- every ordering of {1, 2, 3} should come up about 1/6 of the time +-- (the old algorithm gave some orderings 4/27 and others 5/27) +local runs, tally, uniform = 60000, {}, true +for _ = 1, runs do + local key = table.concat(table.shuffle({ 1, 2, 3 })) + tally[key] = (tally[key] or 0) + 1 +end +local orderings = 0 +for _, n in pairs(tally) do + orderings = orderings + 1 + if math.abs(n - runs / 6) > runs / 6 * 0.05 then uniform = false end +end +check("shuffle is uniform (6 orderings, +-5%)", { orderings, uniform }, { 6, true }) + +check("reverse({1, 2, 3}) (in place)", table.reverse({ 1, 2, 3 }), { 3, 2, 1 }) +check("slice({1..5}, 2, 4)", table.slice({ 1, 2, 3, 4, 5 }, 2, 4), { 2, 3, 4 }) +check("slice({1..5}, -2) (from the end)", table.slice({ 1, 2, 3, 4, 5 }, -2), { 4, 5 }) +check("find({\"a\",\"b\",\"c\"}, \"b\")", table.find({ "a", "b", "c" }, "b"), 2) +check("find(t, missing) -> nil", table.find({ "a" }, "z"), nil) + +local original = { 1, inner = { 2, 3 } } +local copy = table.clone(original) +check("clone(t) has the same content", copy, original) +check("...but is a deep copy", { rawequal(copy, original), rawequal(copy.inner, original.inner) }, { false, false }) + +check("merge({1,2}, {2,3}) (keeps dups)", table.merge({ 1, 2 }, { 2, 3 }), { 1, 2, 2, 3 }) +check("unique({1,2,2,3,1})", table.unique({ 1, 2, 2, 3, 1 }), { 1, 2, 3 }) +check("keyList({10, x = 20})", sorted(table.keyList({ 10, x = 20 })), { 1, "x" }) +check("valueList({10, x = 20})", sorted(table.valueList({ 10, x = 20 })), { 10, 20 }) +check("valueSequence({1, 2, x = 3})", table.valueSequence({ 1, 2, x = 3 }), { 1, 2 }) + +local t1 = { 1, 2, 3, x = { 4, 5 } } +local t2 = { 1, 2, 3, 4, 5 } +check("equal(t1, t2) (array part only)", table.equal(t1, t2), false) +check("equal(t1, t2, true) (deep)", table.equal(t1, t2, true), true) + +local person = { name = "Ada", born = 1815, field = "maths", city = "London", + langs = { "en", "fr" }, notes = { first = "program" } } +check("deep equal ignores pairs order", table.equal(person, reordered(person), true), true) +check("deep equal: table keys by content", + table.equal({ [{ 1 }] = "a", [{ 2 }] = "b" }, { [{ 2 }] = "b", [{ 1 }] = "a" }, true), true) + +----------------------------------------------------------------------------------------- +section("set utils") +----------------------------------------------------------------------------------------- +check("union({1,2}, {2,3})", table.union({ 1, 2 }, { 2, 3 }), { 1, 2, 3 }) +check("negation({1,2,3}, {2})", table.negation({ 1, 2, 3 }, { 2 }), { 1, 3 }) +check("intersect({1,2,3}, {2,3,4})", table.intersect({ 1, 2, 3 }, { 2, 3, 4 }), { 2, 3 }) +check("keySet({\"a\", x = \"b\"})", table.keySet({ "a", x = "b" }), { true, x = true }) +check("valueSet({\"a\", \"a\", \"b\"})", table.valueSet({ "a", "a", "b" }), { a = true, b = true }) + +----------------------------------------------------------------------------------------- +section("methods on enhanced tables") +----------------------------------------------------------------------------------------- +local tb = table { "a", "b", "c", x = "hash" } + +check("tb:at(1), tb:at(-1)", { tb:at(1), tb:at(-1) }, { "a", "c" }) +check("tb:at(10, \"default\")", tb:at(10, "default"), "default") +check("tb:get(\"x\"), tb:get(\"nope\", 0)", { tb:get("x"), tb:get("nope", 0) }, { "hash", 0 }) +check("tb:get(\"sum\", \"none\") (no leak)", tb:get("sum", "none"), "none") +check("table{false}:at(1, \"d\")", table { false }:at(1, "d"), false) +check("tb:first(), tb:last()", { tb:first(), tb:last() }, { "a", "c" }) +check("tb:has(\"b\"), tb:has(\"z\")", { tb:has("b"), tb:has("z") }, { true, false }) +check("tb:haskey(\"x\"), tb:haskey(\"map\")", { tb:haskey("x"), tb:haskey("map") }, { true, false }) +check("tb:empty(), table{x=1}:empty()", { tb:empty(), table { x = 1 }:empty() }, { false, true }) + +local list = table { 2, 3 } +list:append(4, 5) +check("append(4, 5)", list, { 2, 3, 4, 5 }) +list:push(0, 1) +check("push(0, 1) (to the front)", list, { 0, 1, 2, 3, 4, 5 }) +check("pop() returns the last value", list:pop(), 5) +check("head() returns the first value", list:head(), 0) +check("...leaving", list, { 1, 2, 3, 4 }) + +local shifty = table { 1, 2, 3, 4, 5, 6 } +check("lshift(2) returns the first two", { shifty:lshift(2) }, { 1, 2 }) +check("rshift(2) returns the last two", { shifty:rshift(2) }, { 5, 6 }) +check("shift(-1) == lshift(1)", { shifty:shift(-1) }, { 3 }) +check("shift(1) == rshift(1)", { shifty:shift(1) }, { 4 }) +check("...leaving an empty table", shifty, {}) + +local clearable = table { 1, 2, x = 3 } +check("clear() keeps hash keys", clearable:clear(), { x = 3 }) +check("clear(true) removes everything", clearable:clear(true), {}) + +----------------------------------------------------------------------------------------- +section("operator overloads and printing") +----------------------------------------------------------------------------------------- +local a, b = table { 1, 2, 3 }, table { 2, 4, 5 } +check("a + b (union)", a + b, { 1, 2, 3, 4, 5 }) +check("a - b (negation)", a - b, { 1, 3 }) +check("a * b (intersect)", a * b, { 2 }) +check("a .. b (merge)", a .. b, { 1, 2, 3, 2, 4, 5 }) +check("a == b, a == table{1,2,3}", { a == b, a == table { 1, 2, 3 } }, { false, true }) + +print(" print(table { 1, x = { 2 } }) ->") +print(table { 1, x = { 2 } }) +check("tostring renders key/value lines", tostring(table { 1 }):find("k: 1, v: 1", 1, true) ~= nil, true) + +----------------------------------------------------------------------------------------- +section("cyclic tables") +----------------------------------------------------------------------------------------- +local cyc = table { 1, 2 } +cyc[3] = cyc +cyc.me = cyc + +check("flat skips the back-reference", table.flat(cyc), { 1, 2 }) +check("deepflat too", table.deepflat(cyc), { 1, 2 }) +local cyc_copy = table.clone(cyc) +check("clone reproduces the cycle", { rawequal(cyc_copy.me, cyc_copy), rawequal(cyc_copy, cyc) }, { true, false }) +local cyc_pure = table.purify(cyc) +check("purify reproduces the cycle", rawequal(cyc_pure.me, cyc_pure), true) +check("equal(cyc, cyc, true) terminates", table.equal(cyc, cyc, true), true) +check("tostring marks it as ", tostring(cyc):find("", 1, true) ~= nil, true) + +----------------------------------------------------------------------------------------- +section("argument checks and warnings") +----------------------------------------------------------------------------------------- +-- note: no `return` before table.map. A tail call (`return f()`) discards the caller's +-- stack frame, so Lua could no longer say which line the call came from. +local call_line = debug.getinfo(1, "l").currentline + 1 -- the line of the next statement +local ok, msg = pcall(function() table.map(nil, print) end) +print(" map(nil, print) raised: " .. strip_ansi(msg)) +check("map(nil, f) raises an error", { ok, msg:find("table.map()", 1, true) ~= nil }, { false, true }) +check("...reported at the caller's line", { msg:find("regression%.lua:" .. call_line .. ":") ~= nil, + msg:find("luatable.lua", 1, true) ~= nil }, { true, false }) + +ok, msg = pcall(table.zeros, "three") +check("zeros(\"three\") raises an error", { ok, msg:find("table.zeros()", 1, true) ~= nil }, { false, true }) + +ok, msg = pcall(function() return table { 1 }:lshift(-1) end) +check("lshift(-1) raises an error", { ok, msg:find("table.lshift()", 1, true) ~= nil }, { false, true }) + +print(" slice(t, 3, 1) prints a warning and returns {}:") +check("slice({1,2,3}, 3, 1)", table.slice({ 1, 2, 3 }, 3, 1), {}) + +----------------------------------------------------------------------------------------- +print(("\n%d checks: %d passed, %d failed"):format(passed + failed, passed, failed)) +os.exit(failed == 0 and 0 or 1) diff --git a/spec/utility_spec.lua b/spec/utility_spec.lua index 2608049..0d1f10f 100644 --- a/spec/utility_spec.lua +++ b/spec/utility_spec.lua @@ -4,6 +4,24 @@ local plain, is_enhanced, sorted = h.plain, h.is_enhanced, h.sorted describe("utility", function() + describe("table.info", function() + -- info() prints through a cached `print`, so check its text in the source instead + local function read(path) + local f = assert(io.open(path, "rb")) + local text = f:read("*a") + f:close() + return text + end + + it("reports a version that has a release rockspec", function() + local version = read("src/luatable.lua"):match("function table%.info%(%).-version: ([%d.]+)") + assert.are.equal("0.8.0", version) + local rockspec = read("rockspecs/luatable-" .. version .. "-1.rockspec") + assert.are.equal(version .. "-1", rockspec:match('version = "([^"]+)"')) + assert.are.equal("v" .. version, rockspec:match('tag = "([^"]+)"')) + end) + end) + describe("table.purify", function() it("keeps array values and hash pairs", function() assert.are.same({ 1, 2, x = 3 }, plain(T.purify({ 1, 2, x = 3 }))) @@ -115,6 +133,32 @@ describe("utility", function() local t = { 1, 2, 3 } assert.is_true(rawequal(t, T.shuffle(t))) end) + + it("leaves empty and one-element tables unchanged", function() + assert.are.same({}, T.shuffle({})) + assert.are.same({ 7 }, T.shuffle({ 7 })) + end) + + it("makes every ordering equally likely", function() + -- regression: the old algorithm gave some orderings 4/27 and others 5/27 + local runs, counts = 60000, {} + + for _ = 1, runs do + local key = table.concat(T.shuffle({ 1, 2, 3 })) + counts[key] = (counts[key] or 0) + 1 + end + + local expected = runs / 6 + local orderings = 0 + + for key, n in pairs(counts) do + orderings = orderings + 1 + assert.is_true(math.abs(n - expected) <= expected * 0.05, + ("ordering %s came up %d times, expected about %d"):format(key, n, expected)) + end + + assert.are.equal(6, orderings) + end) end) describe("table.reverse", function() @@ -264,6 +308,25 @@ describe("utility", function() assert.is_false(T.equal({ { 1 }, 2 }, { 2, 1 })) end) + it("deep equality does not depend on pairs order", function() + local t = { 1, 2, alpha = 1, bravo = { 2, 3 }, charlie = "x", delta = 4, + echo = { y = 5 }, foxtrot = 6, golf = true, hotel = 8, india = 9, + juliet = { 10, { 11 } } } + assert.is_true(T.equal(t, h.reordered(t), true)) + + local words = { alpha = 1, bravo = 2, charlie = 3, delta = 4, echo = 5, + foxtrot = 6, golf = 7, hotel = 8, india = 9, juliet = 10 } + assert.is_true(T.equal(words, h.reordered(words), true)) + assert.is_true(T.equal(h.reordered(words), words, true)) + end) + + it("deep equality treats equal-content table keys alike", function() + local a = { [{ 1 }] = "one", [{ 2 }] = "two", [{ 3, 4 }] = "pair" } + local b = { [{ 3, 4 }] = "pair", [{ 2 }] = "two", [{ 1 }] = "one" } + assert.is_true(T.equal(a, b, true)) + assert.is_false(T.equal(a, { [{ 1 }] = "two", [{ 2 }] = "one", [{ 3, 4 }] = "pair" }, true)) + end) + it("terminates on cyclic tables", function() local t = { 1, 2 } t[3] = t diff --git a/src/luatable.lua b/src/luatable.lua index 7c7bf95..c49c970 100644 --- a/src/luatable.lua +++ b/src/luatable.lua @@ -25,8 +25,13 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. --]] ----------------------------------------------------------------------------------------- -local setmetatable = setmetatable +local setmetatable = setmetatable local unpack = table.unpack or unpack +local sort = table.sort +local tostring = tostring +local rawequal = rawequal +local yield = coroutine.yield +local wrap = coroutine.wrap local select = select local error = error local print = print @@ -133,7 +138,7 @@ function table.info() -- print library info print [[ luatable [ - version: 0.7, + version: 0.8.0, author: Luca Anzalone, github: https://github.com/Luca96/lua-table ] @@ -491,10 +496,124 @@ function table.reject(t, criteria, ...) return tb end -local function flat_into(result, items, deep, path) --- depth-first: appends the non-table values of items to result, in order. +-- flat_into, seq_at and compare call each other, so they are declared up front +local flat_into, seq_at, compare + +-- rank of each key type in the deepflat order; any other type ranks last +local rank = { number = 1, string = 2, boolean = 3, table = 4 } + +seq_at = function(t, i, ctx) +-- returns the i-th value of t's canonical sequence (its deepflat), or nil past +-- the end. The sequence is produced lazily by a coroutine and remembered in +-- ctx.seqs, so a comparison only flattens as far as the first difference. +-- ctx.path holds the ancestors of the table being sorted: like in flat_into, +-- they are cycles, so an ancestor has an empty sequence. + if ctx.path[t] then + return nil + end + + local s = ctx.seqs[t] + + if s == nil then + local path = {} + + for k in pairs(ctx.path) do + path[k] = true + end + + local function emit(v) + if v ~= nil then + yield(v) + end + end + + s = { n = 0, gen = wrap(function() flat_into(emit, t, true, path) end) } + ctx.seqs[t] = s + end + + while s.n < i and s.gen do + local v = s.gen() + + if v == nil then + s.gen = nil + else + s.n = s.n + 1 + s[s.n] = v + end + end + + return s[i] +end + +compare = function(a, b, ctx) +-- total order used by deepflat for hash keys: returns -1, 0 or 1. +-- numbers < strings < booleans < tables < other types; tables compare by +-- content (their deepflat, element by element, stopping at the first +-- difference); functions, userdata and threads can only compare by identity. + if rawequal(a, b) then + return 0 + end + + local ta, tb = type(a), type(b) + local ra, rb = rank[ta] or 5, rank[tb] or 5 + + if ra ~= rb then + return ra < rb and -1 or 1 + end + + if ta == "number" then + -- NaN is not ordered by <, so it goes after every other number + local na, nb = a ~= a, b ~= b + + if na or nb then + if na and nb then return 0 end + return na and 1 or -1 + end + + return a < b and -1 or (b < a and 1 or 0) + + elseif ta == "string" then + return a < b and -1 or (b < a and 1 or 0) + + elseif ta == "boolean" then + return a and 1 or -1 -- a ~= b here, so false comes first + + elseif ta == "table" then + local i = 1 + + while true do + local x, y = seq_at(a, i, ctx), seq_at(b, i, ctx) + + if x == nil or y == nil then + -- a sequence that ends first (a prefix of the other) comes first + if x == nil and y == nil then return 0 end + return x == nil and -1 or 1 + end + + local c = compare(x, y, ctx) + + if c ~= 0 then + return c + end + + i = i + 1 + end + end + + if ta ~= tb then + return ta < tb and -1 or 1 + end + + local sa, sb = tostring(a), tostring(b) + + return sa < sb and -1 or (sb < sa and 1 or 0) +end + +flat_into = function(emit, items, deep, path) +-- depth-first: passes the non-table values of items to emit, in order. -- The array part (1..#items) comes first; if deep is true, the remaining --- key-value pairs follow (in pairs order). +-- key-value pairs follow, sorted by key (see compare) and, for keys that +-- compare equal, by value, so the result never depends on pairs order. -- path holds items and its ancestors: a nested table already in path is a -- cycle and is skipped. Shared (non-cyclic) tables are flattened each time. local n = #items @@ -503,10 +622,10 @@ local function flat_into(result, items, deep, path) local function add(v) if type(v) == "table" then if not path[v] then - flat_into(result, v, deep, path) + flat_into(emit, v, deep, path) end else - result[#result + 1] = v + emit(v) end end @@ -515,32 +634,67 @@ local function flat_into(result, items, deep, path) end if deep then + local entries = {} + for k, v in pairs(items) do local in_array = type(k) == "number" and k >= 1 and k <= n and floor(k) == k if not in_array then - add(v) + entries[#entries + 1] = { k, v } end end + + if #entries > 1 then + -- one context per sort: path is stable while sorting, and the cached + -- sequences are only valid for that path + local ctx = { path = path, seqs = {} } + + sort(entries, function(x, y) + local c = compare(x[1], y[1], ctx) + + if c == 0 then + c = compare(x[2], y[2], ctx) + end + + return c < 0 + end) + end + + for i = 1, #entries do + add(entries[i][2]) + end end path[items] = nil +end - return result +local function appender(result) +-- emit function that appends to result (nil values are dropped) + return function(v) + result[#result + 1] = v + end end function table.flat(t) -- flattens a nested table (over int indices - use table.deepflat instead) assert_table("flat", t) - return flat_into(table(), t, false, {}) + local result = table() + flat_into(appender(result), t, false, {}) + + return result end function table.deepflat(t) --- flattens a nested table over all key-value pairs +-- flattens a nested table over all key-value pairs: the array part first, then +-- the other keys in sorted order (numbers, strings, booleans, tables by content, +-- then other types by identity) assert_table("deepflat", t) - return flat_into(table(), t, true, {}) + local result = table() + flat_into(appender(result), t, true, {}) + + return result end function table.flatmap(t, func, ...) @@ -718,13 +872,12 @@ function table.sample(t) end function table.shuffle(t) --- mix the values inside the given table +-- mix the values inside the given table (Fisher-Yates: every ordering is +-- equally likely) assert_table("shuffle", t) - local len = #t - - for i = 1, len do - local k = random(len) + for i = #t, 2, -1 do + local k = random(i) t[i], t[k] = t[k], t[i] end @@ -1266,8 +1419,17 @@ function table.new(...) return setmetatable(t, mt) end +function table.of(...) +-- creates an enhanched table whose elements are exactly the given arguments. +-- Unlike table.new, a single table argument becomes the only element +-- (table.of(t) is { t }), and its own metatable is left alone. + return setmetatable({ ... }, mt) +end + function table.init(size, def, ...) --- fill the enhanched table with a custom init value or function +-- fill the enhanched table with a custom init value or function. +-- a function is called as def(i, ...) for each slot; a table is deep-copied +-- into each slot (copies are enhanced tables), so slots never share it assert_number("init", size) local t = table() @@ -1277,7 +1439,12 @@ function table.init(size, def, ...) for i = 1, size do t[i] = def(i, ...) end - else + elseif type(def) == "table" then + -- a fresh seen per slot: copies share nothing with each other + for i = 1, size do + t[i] = clone_rec(def, {}) + end + else -- for i = 1, size do t[i] = def