• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

lunarmodules / Penlight / 24663963073

20 Apr 2026 11:27AM UTC coverage: 90.174%. Remained the same
24663963073

push

github

web-flow
chore(docs): typo author name in template preprocessor (#522)

5543 of 6147 relevant lines covered (90.17%)

822.15 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

97.8
/lua/pl/tablex.lua
1
--- Extended operations on Lua tables.
2
--
3
-- See @{02-arrays.md.Useful_Operations_on_Tables|the Guide}
4
--
5
-- Dependencies: `pl.utils`, `pl.types`
6
-- @module pl.tablex
7
local utils = require ('pl.utils')
665✔
8
local types = require ('pl.types')
665✔
9
local getmetatable,setmetatable,require = getmetatable,setmetatable,require
665✔
10
local tsort,append,remove = table.sort,table.insert,table.remove
665✔
11
local min = math.min
665✔
12
local pairs,type,unpack,select,tostring = pairs,type,utils.unpack,select,tostring
665✔
13
local function_arg = utils.function_arg
665✔
14
local assert_arg = utils.assert_arg
665✔
15

16
local tablex = {}
665✔
17

18
-- generally, functions that make copies of tables try to preserve the metatable.
19
-- However, when the source has no obvious type, then we attach appropriate metatables
20
-- like List, Map, etc to the result.
21
local function setmeta (res,tbl,pl_class)
22
    local mt = getmetatable(tbl) or pl_class and require('pl.' .. pl_class)
4,750✔
23
    return mt and setmetatable(res, mt) or res
4,750✔
24
end
25

26
local function makelist(l)
27
    return setmetatable(l, require('pl.List'))
133✔
28
end
29

30
local function makemap(m)
31
    return setmetatable(m, require('pl.Map'))
57✔
32
end
33

34
local function complain (idx,msg)
35
    error(('argument %d is not %s'):format(idx,msg),3)
×
36
end
37

38
local function assert_arg_indexable (idx,val)
39
    if not types.is_indexable(val) then
4,200✔
40
        complain(idx,"indexable")
×
41
    end
42
end
43

44
local function assert_arg_iterable (idx,val)
45
    if not types.is_iterable(val) then
6,588✔
46
        complain(idx,"iterable")
×
47
    end
48
end
49

50
local function assert_arg_writeable (idx,val)
51
    if not types.is_writeable(val) then
48✔
52
        complain(idx,"writeable")
×
53
    end
54
end
55

56
--- copy a table into another, in-place.
57
-- @within Copying
58
-- @tab t1 destination table
59
-- @tab t2 source (actually any iterable object)
60
-- @return first table
61
function tablex.update (t1,t2)
665✔
62
    assert_arg_writeable(1,t1)
38✔
63
    assert_arg_iterable(2,t2)
38✔
64
    for k,v in pairs(t2) do
171✔
65
        t1[k] = v
133✔
66
    end
67
    return t1
38✔
68
end
69

70
--- total number of elements in this table.
71
-- Note that this is distinct from `#t`, which is the number
72
-- of values in the array part; this value will always
73
-- be greater or equal. The difference gives the size of
74
-- the hash part, for practical purposes. Works for any
75
-- object with a __pairs metamethod.
76
-- @tab t a table
77
-- @return the size
78
function tablex.size (t)
665✔
79
    assert_arg_iterable(1,t)
57✔
80
    local i = 0
57✔
81
    for k in pairs(t) do i = i + 1 end
133✔
82
    return i
57✔
83
end
84

85
--- make a shallow copy of a table
86
-- @within Copying
87
-- @tab t an iterable source
88
-- @return new table
89
function tablex.copy (t)
665✔
90
    assert_arg_iterable(1,t)
532✔
91
    local res = {}
532✔
92
    for k,v in pairs(t) do
29,049✔
93
        res[k] = v
28,517✔
94
    end
95
    return res
532✔
96
end
97

98
local function cycle_aware_copy(t, cache)
99
    if type(t) ~= 'table' then return t end
1,178✔
100
    if cache[t] then return cache[t] end
209✔
101
    assert_arg_iterable(1,t)
190✔
102
    local res = {}
190✔
103
    cache[t] = res
190✔
104
    local mt = getmetatable(t)
190✔
105
    for k,v in pairs(t) do
703✔
106
        res[cycle_aware_copy(k, cache)] = cycle_aware_copy(v, cache)
783✔
107
    end
108
    setmetatable(res,mt)
190✔
109
    return res
190✔
110
end
111

112
--- make a deep copy of a table, recursively copying all the keys and fields.
113
-- This supports cycles in tables; cycles will be reproduced in the copy.
114
-- This will also set the copied table's metatable to that of the original.
115
-- @within Copying
116
-- @tab t A table
117
-- @return new table
118
function tablex.deepcopy(t)
665✔
119
    return cycle_aware_copy(t,{})
152✔
120
end
121

122
local abs = math.abs
665✔
123

124
local function cycle_aware_compare(t1,t2,ignore_mt,eps,cache)
125
    if cache[t1] and cache[t1][t2] then return true end
26,515✔
126
    local ty1 = type(t1)
26,496✔
127
    local ty2 = type(t2)
26,496✔
128
    if ty1 ~= ty2 then return false end
26,496✔
129
    -- non-table types can be directly compared
130
    if ty1 ~= 'table' then
26,496✔
131
        if ty1 == 'number' and eps then return abs(t1-t2) < eps end
18,179✔
132
        return t1 == t2
17,519✔
133
    end
134
    -- as well as tables which have the metamethod __eq
135
    local mt = getmetatable(t1)
8,317✔
136
    if not ignore_mt and mt and mt.__eq then return t1 == t2 end
8,317✔
137
    for k1 in pairs(t1) do
29,822✔
138
        if t2[k1]==nil then return false end
21,505✔
139
    end
140
    for k2 in pairs(t2) do
29,822✔
141
        if t1[k2]==nil then return false end
21,505✔
142
    end
143
    cache[t1] = cache[t1] or {}
8,317✔
144
    cache[t1][t2] = true
8,317✔
145
    for k1,v1 in pairs(t1) do
29,822✔
146
        local v2 = t2[k1]
21,505✔
147
        if not cycle_aware_compare(v1,v2,ignore_mt,eps,cache) then return false end
27,610✔
148
    end
149
    return true
8,317✔
150
end
151

152
--- compare two values.
153
-- if they are tables, then compare their keys and fields recursively.
154
-- @within Comparing
155
-- @param t1 A value
156
-- @param t2 A value
157
-- @bool[opt] ignore_mt if true, ignore __eq metamethod (default false)
158
-- @number[opt] eps if defined, then used for any number comparisons
159
-- @return true or false
160
function tablex.deepcompare(t1,t2,ignore_mt,eps)
665✔
161
    return cycle_aware_compare(t1,t2,ignore_mt,eps,{})
5,010✔
162
end
163

164
--- compare two arrays using a predicate.
165
-- @within Comparing
166
-- @array t1 an array
167
-- @array t2 an array
168
-- @func cmp A comparison function; `bool = cmp(t1_value, t2_value)`
169
-- @return true or false
170
-- @usage
171
-- assert(tablex.compare({ 1, 2, 3 }, { 1, 2, 3 }, "=="))
172
--
173
-- assert(tablex.compare(
174
--    {1,2,3, hello = "world"},  -- fields are not compared!
175
--    {1,2,3}, function(v1, v2) return v1 == v2 end)
176
function tablex.compare (t1,t2,cmp)
665✔
177
    assert_arg_indexable(1,t1)
76✔
178
    assert_arg_indexable(2,t2)
76✔
179
    if #t1 ~= #t2 then return false end
76✔
180
    cmp = function_arg(3,cmp)
96✔
181
    for k = 1,#t1 do
209✔
182
        if not cmp(t1[k],t2[k]) then return false end
192✔
183
    end
184
    return true
57✔
185
end
186

187
--- compare two list-like tables using an optional predicate, without regard for element order.
188
-- @within Comparing
189
-- @array t1 a list-like table
190
-- @array t2 a list-like table
191
-- @param cmp A comparison function (may be nil)
192
function tablex.compare_no_order (t1,t2,cmp)
665✔
193
    assert_arg_indexable(1,t1)
133✔
194
    assert_arg_indexable(2,t2)
133✔
195
    if cmp then cmp = function_arg(3,cmp) end
133✔
196
    if #t1 ~= #t2 then return false end
133✔
197
    local visited = {}
133✔
198
    for i = 1,#t1 do
494✔
199
        local val = t1[i]
380✔
200
        local gotcha
201
        for j = 1,#t2 do
798✔
202
            if not visited[j] then
779✔
203
                local match
204
                if cmp then match = cmp(val,t2[j]) else match = val == t2[j] end
512✔
205
                if match then
512✔
206
                    gotcha = j
361✔
207
                    break
247✔
208
                end
209
            end
210
        end
211
        if not gotcha then return false end
380✔
212
        visited[gotcha] = true
361✔
213
    end
214
    return true
114✔
215
end
216

217

218
--- return the index of a value in a list.
219
-- Like string.find, there is an optional index to start searching,
220
-- which can be negative.
221
-- @within Finding
222
-- @array t A list-like table
223
-- @param val A value
224
-- @int idx index to start; -1 means last element,etc (default 1)
225
-- @return index of value or nil if not found
226
-- @usage find({10,20,30},20) == 2
227
-- @usage find({'a','b','a','c'},'a',2) == 3
228
function tablex.find(t,val,idx)
665✔
229
    assert_arg_indexable(1,t)
95✔
230
    idx = idx or 1
95✔
231
    if idx < 0 then idx = #t + idx + 1 end
95✔
232
    for i = idx,#t do
437✔
233
        if t[i] == val then return i end
418✔
234
    end
235
    return nil
19✔
236
end
237

238
--- return the index of a value in a list, searching from the end.
239
-- Like string.find, there is an optional index to start searching,
240
-- which can be negative.
241
-- @within Finding
242
-- @array t A list-like table
243
-- @param val A value
244
-- @param idx index to start; -1 means last element,etc (default `#t`)
245
-- @return index of value or nil if not found
246
-- @usage rfind({10,10,10},10) == 3
247
function tablex.rfind(t,val,idx)
665✔
248
    assert_arg_indexable(1,t)
133✔
249
    idx = idx or #t
133✔
250
    if idx < 0 then idx = #t + idx + 1 end
133✔
251
    for i = idx,1,-1 do
323✔
252
        if t[i] == val then return i end
266✔
253
    end
254
    return nil
57✔
255
end
256

257

258
--- return the index (or key) of a value in a table using a comparison function.
259
--
260
-- *NOTE*: the 2nd return value of this function, the value returned
261
-- by the comparison function, has a limitation that it cannot be `false`.
262
-- Because if it is, then it indicates the comparison failed, and the
263
-- function will continue the search. See examples.
264
-- @within Finding
265
-- @tab t A table
266
-- @func cmp A comparison function
267
-- @param arg an optional second argument to the function
268
-- @return index of value, or nil if not found
269
-- @return value returned by comparison function (cannot be `false`!)
270
-- @usage
271
-- -- using an operator
272
-- local lst = { "Rudolph", true, false, 15 }
273
-- local idx, cmp_result = tablex.rfind(lst, "==", "Rudolph")
274
-- assert(idx == 1)
275
-- assert(cmp_result == true)
276
--
277
-- local idx, cmp_result = tablex.rfind(lst, "==", false)
278
-- assert(idx == 3)
279
-- assert(cmp_result == true)       -- looking up 'false' works!
280
--
281
-- -- using a function returning the value looked up
282
-- local cmp = function(v1, v2) return v1 == v2 and v2 end
283
-- local idx, cmp_result = tablex.rfind(lst, cmp, "Rudolph")
284
-- assert(idx == 1)
285
-- assert(cmp_result == "Rudolph")  -- the value is returned
286
--
287
-- -- NOTE: this fails, since 'false' cannot be returned!
288
-- local idx, cmp_result = tablex.rfind(lst, cmp, false)
289
-- assert(idx == nil)               -- looking up 'false' failed!
290
-- assert(cmp_result == nil)
291
function tablex.find_if(t,cmp,arg)
665✔
292
    assert_arg_iterable(1,t)
152✔
293
    cmp = function_arg(2,cmp)
192✔
294
    for k,v in pairs(t) do
418✔
295
        local c = cmp(v,arg)
399✔
296
        if c then return k,c end
399✔
297
    end
298
    return nil
19✔
299
end
300

301
--- return a list of all values in a table indexed by another list.
302
-- @tab tbl a table
303
-- @array idx an index table (a list of keys)
304
-- @return a list-like table
305
-- @usage index_by({10,20,30,40},{2,4}) == {20,40}
306
-- @usage index_by({one=1,two=2,three=3},{'one','three'}) == {1,3}
307
function tablex.index_by(tbl,idx)
665✔
308
    assert_arg_indexable(1,tbl)
190✔
309
    assert_arg_indexable(2,idx)
190✔
310
    local res = {}
190✔
311
    for i = 1,#idx do
627✔
312
        res[i] = tbl[idx[i]]
437✔
313
    end
314
    return setmeta(res,tbl,'List')
190✔
315
end
316

317
--- apply a function to all values of a table.
318
-- This returns a table of the results.
319
-- Any extra arguments are passed to the function.
320
-- @within MappingAndFiltering
321
-- @func fun A function that takes at least one argument
322
-- @tab t A table
323
-- @param ... optional arguments
324
-- @usage map(function(v) return v*v end, {10,20,30,fred=2}) is {100,400,900,fred=4}
325
function tablex.map(fun,t,...)
665✔
326
    assert_arg_iterable(1,t)
3,040✔
327
    fun = function_arg(1,fun)
3,840✔
328
    local res = {}
3,040✔
329
    for k,v in pairs(t) do
11,267✔
330
        res[k] = fun(v,...)
10,122✔
331
    end
332
    return setmeta(res,t)
3,040✔
333
end
334

335
--- apply a function to all values of a list.
336
-- This returns a table of the results.
337
-- Any extra arguments are passed to the function.
338
-- @within MappingAndFiltering
339
-- @func fun A function that takes at least one argument
340
-- @array t a table (applies to array part)
341
-- @param ... optional arguments
342
-- @return a list-like table
343
-- @usage imap(function(v) return v*v end, {10,20,30,fred=2}) is {100,400,900}
344
function tablex.imap(fun,t,...)
665✔
345
    assert_arg_indexable(1,t)
874✔
346
    fun = function_arg(1,fun)
1,104✔
347
    local res = {}
874✔
348
    for i = 1,#t do
5,225✔
349
        res[i] = fun(t[i],...) or false
5,391✔
350
    end
351
    return setmeta(res,t,'List')
874✔
352
end
353

354
--- apply a named method to values from a table.
355
-- @within MappingAndFiltering
356
-- @string name the method name
357
-- @array t a list-like table
358
-- @param ... any extra arguments to the method
359
-- @return a `List` with the results of the method (1st result only)
360
-- @usage
361
-- local Car = {}
362
-- Car.__index = Car
363
-- function Car.new(car)
364
--   return setmetatable(car or {}, Car)
365
-- end
366
-- Car.speed = 0
367
-- function Car:faster(increase)
368
--   self.speed = self.speed + increase
369
--   return self.speed
370
-- end
371
--
372
-- local ferrari = Car.new{ name = "Ferrari" }
373
-- local lamborghini = Car.new{ name = "Lamborghini", speed = 50 }
374
-- local cars = { ferrari, lamborghini }
375
--
376
-- assert(ferrari.speed == 0)
377
-- assert(lamborghini.speed == 50)
378
-- tablex.map_named_method("faster", cars, 10)
379
-- assert(ferrari.speed == 10)
380
-- assert(lamborghini.speed == 60)
381
function tablex.map_named_method (name,t,...)
665✔
382
    utils.assert_string(1,name)
19✔
383
    assert_arg_indexable(2,t)
19✔
384
    local res = {}
19✔
385
    for i = 1,#t do
57✔
386
        local val = t[i]
38✔
387
        local fun = val[name]
38✔
388
        res[i] = fun(val,...)
48✔
389
    end
390
    return setmeta(res,t,'List')
19✔
391
end
392

393
--- apply a function to all values of a table, in-place.
394
-- Any extra arguments are passed to the function.
395
-- @func fun A function that takes at least one argument
396
-- @tab t a table
397
-- @param ... extra arguments passed to `fun`
398
-- @see tablex.foreach
399
function tablex.transform (fun,t,...)
665✔
400
    assert_arg_iterable(1,t)
38✔
401
    fun = function_arg(1,fun)
48✔
402
    for k,v in pairs(t) do
133✔
403
        t[k] = fun(v,...)
120✔
404
    end
405
end
406

407
--- generate a table of all numbers in a range.
408
-- This is consistent with a numerical for loop.
409
-- @int start  number
410
-- @int finish number
411
-- @int[opt=1] step  make this negative for start < finish
412
function tablex.range (start,finish,step)
665✔
413
    local res
414
    step = step or 1
57✔
415
    if start == finish then
57✔
416
        res = {start}
19✔
417
    elseif (start > finish and step > 0) or (finish > start and step < 0) then
38✔
418
        res = {}
19✔
419
    else
420
        local k = 1
19✔
421
        res = {}
19✔
422
        for i=start,finish,step do res[k]=i; k=k+1 end
47✔
423
    end
424
    return makelist(res)
57✔
425
end
426

427
--- apply a function to values from two tables.
428
-- @within MappingAndFiltering
429
-- @func fun a function of at least two arguments
430
-- @tab t1 a table
431
-- @tab t2 a table
432
-- @param ... extra arguments
433
-- @return a table
434
-- @usage map2('+',{1,2,3,m=4},{10,20,30,m=40}) is {11,22,23,m=44}
435
function tablex.map2 (fun,t1,t2,...)
665✔
436
    assert_arg_iterable(1,t1)
190✔
437
    assert_arg_iterable(2,t2)
190✔
438
    fun = function_arg(1,fun)
240✔
439
    local res = {}
190✔
440
    for k,v in pairs(t1) do
589✔
441
        res[k] = fun(v,t2[k],...)
489✔
442
    end
443
    return setmeta(res,t1,'List')
190✔
444
end
445

446
--- apply a function to values from two arrays.
447
-- The result will be the length of the shortest array.
448
-- @within MappingAndFiltering
449
-- @func fun a function of at least two arguments
450
-- @array t1 a list-like table
451
-- @array t2 a list-like table
452
-- @param ... extra arguments
453
-- @usage imap2('+',{1,2,3,m=4},{10,20,30,m=40}) is {11,22,23}
454
function tablex.imap2 (fun,t1,t2,...)
665✔
455
    assert_arg_indexable(2,t1)
95✔
456
    assert_arg_indexable(3,t2)
95✔
457
    fun = function_arg(1,fun)
120✔
458
    local res,n = {},math.min(#t1,#t2)
95✔
459
    for i = 1,n do
304✔
460
        res[i] = fun(t1[i],t2[i],...)
264✔
461
    end
462
    return res
95✔
463
end
464

465
--- 'reduce' a list using a binary function.
466
-- @func fun a function of two arguments
467
-- @array t a list-like table
468
-- @array memo optional initial memo value. Defaults to first value in table.
469
-- @return the result of the function
470
-- @usage reduce('+',{1,2,3,4}) == 10
471
function tablex.reduce (fun,t,memo)
665✔
472
    assert_arg_indexable(2,t)
437✔
473
    fun = function_arg(1,fun)
552✔
474
    local n = #t
437✔
475
    if n == 0 then
437✔
476
        return memo
38✔
477
    end
478
    local res = memo and fun(memo, t[1]) or t[1]
404✔
479
    for i = 2,n do
1,387✔
480
        res = fun(res,t[i])
1,248✔
481
    end
482
    return res
399✔
483
end
484

485
--- apply a function to all elements of a table.
486
-- The arguments to the function will be the value,
487
-- the key and _finally_ any extra arguments passed to this function.
488
-- Note that the Lua 5.0 function table.foreach passed the _key_ first.
489
-- @within Iterating
490
-- @tab t a table
491
-- @func fun a function on the elements; `function(value, key, ...)`
492
-- @param ... extra arguments passed to `fun`
493
-- @see tablex.transform
494
function tablex.foreach(t,fun,...)
665✔
495
    assert_arg_iterable(1,t)
19✔
496
    fun = function_arg(2,fun)
24✔
497
    for k,v in pairs(t) do
95✔
498
        fun(v,k,...)
76✔
499
    end
500
end
501

502
--- apply a function to all elements of a list-like table in order.
503
-- The arguments to the function will be the value,
504
-- the index and _finally_ any extra arguments passed to this function
505
-- @within Iterating
506
-- @array t a table
507
-- @func fun a function with at least one argument
508
-- @param ... optional arguments
509
function tablex.foreachi(t,fun,...)
665✔
510
    assert_arg_indexable(1,t)
19✔
511
    fun = function_arg(2,fun)
24✔
512
    for i = 1,#t do
76✔
513
        fun(t[i],i,...)
57✔
514
    end
515
end
516

517
--- Apply a function to a number of tables.
518
-- A more general version of map
519
-- The result is a table containing the result of applying that function to the
520
-- ith value of each table. Length of output list is the minimum length of all the lists
521
-- @within MappingAndFiltering
522
-- @func fun a function of n arguments
523
-- @tab ... n tables
524
-- @usage mapn(function(x,y,z) return x+y+z end, {1,2,3},{10,20,30},{100,200,300}) is {111,222,333}
525
-- @usage mapn(math.max, {1,20,300},{10,2,3},{100,200,100}) is    {100,200,300}
526
-- @param fun A function that takes as many arguments as there are tables
527
function tablex.mapn(fun,...)
665✔
528
    fun = function_arg(1,fun)
72✔
529
    local res = {}
57✔
530
    local lists = {...}
57✔
531
    if #lists == 0 then return res end
57✔
532
    local minn = 1e40
57✔
533
    for i = 1,#lists do
209✔
534
        minn = min(minn,#(lists[i]))
152✔
535
    end
536
    for i = 1,minn do
228✔
537
        local args,k = {},1
171✔
538
        for j = 1,#lists do
627✔
539
            args[k] = lists[j][i]
456✔
540
            k = k + 1
456✔
541
        end
542
        res[#res+1] = fun(unpack(args))
246✔
543
    end
544
    return res
57✔
545
end
546

547
--- call the function with the key and value pairs from a table.
548
-- The function can return a value and a key (note the order!). If both
549
-- are not nil, then this pair is inserted into the result: if the key already exists, we convert the value for that
550
-- key into a table and append into it. If only value is not nil, then it is appended to the result.
551
-- @within MappingAndFiltering
552
-- @func fun A function which will be passed each key and value as arguments, plus any extra arguments to pairmap.
553
-- @tab t A table
554
-- @param ... optional arguments
555
-- @usage pairmap(function(k,v) return v end,{fred=10,bonzo=20}) is {10,20} _or_ {20,10}
556
-- @usage pairmap(function(k,v) return {k,v},k end,{one=1,two=2}) is {one={'one',1},two={'two',2}}
557
function tablex.pairmap(fun,t,...)
665✔
558
    assert_arg_iterable(1,t)
285✔
559
    fun = function_arg(1,fun)
360✔
560
    local res = {}
285✔
561
    for k,v in pairs(t) do
1,121✔
562
        local rv,rk = fun(k,v,...)
836✔
563
        if rk then
836✔
564
            if res[rk] then
285✔
565
                if type(res[rk]) == 'table' then
38✔
566
                    table.insert(res[rk],rv)
19✔
567
                else
568
                    res[rk] = {res[rk], rv}
19✔
569
                end
570
            else
571
                res[rk] = rv
247✔
572
            end
573
        else
574
            res[#res+1] = rv
551✔
575
        end
576
    end
577
    return res
285✔
578
end
579

580
local function keys_op(i,v) return i end
817✔
581

582
--- return all the keys of a table in arbitrary order.
583
-- @within Extraction
584
-- @tab t A list-like table where the values are the keys of the input table
585
function tablex.keys(t)
665✔
586
    assert_arg_iterable(1,t)
57✔
587
    return makelist(tablex.pairmap(keys_op,t))
72✔
588
end
589

590
local function values_op(i,v) return v end
722✔
591

592
--- return all the values of the table in arbitrary order
593
-- @within Extraction
594
-- @tab t A list-like table where the values are the values of the input table
595
function tablex.values(t)
665✔
596
    assert_arg_iterable(1,t)
19✔
597
    return makelist(tablex.pairmap(values_op,t))
24✔
598
end
599

600
local function index_map_op (i,v) return i,v end
817✔
601

602
--- create an index map from a list-like table. The original values become keys,
603
-- and the associated values are the indices into the original list.
604
-- @array t a list-like table
605
-- @return a map-like table
606
function tablex.index_map (t)
665✔
607
    assert_arg_indexable(1,t)
38✔
608
    return makemap(tablex.pairmap(index_map_op,t))
48✔
609
end
610

611
local function set_op(i,v) return true,v end
665✔
612

613
--- create a set from a list-like table. A set is a table where the original values
614
-- become keys, and the associated values are all true.
615
-- @array t a list-like table
616
-- @return a set (a map-like table)
617
function tablex.makeset (t)
665✔
618
    assert_arg_indexable(1,t)
×
619
    return setmetatable(tablex.pairmap(set_op,t),require('pl.Set'))
×
620
end
621

622
--- combine two tables, either as union or intersection. Corresponds to
623
-- set operations for sets () but more general. Not particularly
624
-- useful for list-like tables.
625
-- @within Merging
626
-- @tab t1 a table
627
-- @tab t2 a table
628
-- @bool dup true for a union, false for an intersection.
629
-- @usage merge({alice=23,fred=34},{bob=25,fred=34}) is {fred=34}
630
-- @usage merge({alice=23,fred=34},{bob=25,fred=34},true) is {bob=25,fred=34,alice=23}
631
-- @see tablex.index_map
632
function tablex.merge (t1,t2,dup)
665✔
633
    assert_arg_iterable(1,t1)
114✔
634
    assert_arg_iterable(2,t2)
114✔
635
    local res = {}
114✔
636
    for k,v in pairs(t1) do
388✔
637
        if dup or t2[k] then res[k] = v end
266✔
638
    end
639
    if dup then
114✔
640
      for k,v in pairs(t2) do
152✔
641
        res[k] = v
95✔
642
      end
643
    end
644
    return setmeta(res,t1,'Map')
114✔
645
end
646

647
--- the union of two map-like tables.
648
-- If there are duplicate keys, the second table wins.
649
-- @tab t1 a table
650
-- @tab t2 a table
651
-- @treturn tab
652
-- @see tablex.merge
653
function tablex.union(t1, t2)
665✔
654
    return tablex.merge(t1, t2, true)
×
655
end
656

657
--- the intersection of two map-like tables.
658
-- @tab t1 a table
659
-- @tab t2 a table
660
-- @treturn tab
661
-- @see tablex.merge
662
function tablex.intersection(t1, t2)
665✔
663
    return tablex.merge(t1, t2, false)
×
664
end
665

666
--- a new table which is the difference of two tables.
667
-- With sets (where the values are all true) this is set difference and
668
-- symmetric difference depending on the third parameter.
669
-- @within Merging
670
-- @tab s1 a map-like table or set
671
-- @tab s2 a map-like table or set
672
-- @bool symm symmetric difference (default false)
673
-- @return a map-like table or set
674
function tablex.difference (s1,s2,symm)
665✔
675
    assert_arg_iterable(1,s1)
114✔
676
    assert_arg_iterable(2,s2)
114✔
677
    local res = {}
114✔
678
    for k,v in pairs(s1) do
304✔
679
        if s2[k] == nil then res[k] = v end
190✔
680
    end
681
    if symm then
114✔
682
        for k,v in pairs(s2) do
95✔
683
            if s1[k] == nil then res[k] = v end
57✔
684
        end
685
    end
686
    return setmeta(res,s1,'Map')
114✔
687
end
688

689
--- A table where the key/values are the values and value counts of the table.
690
-- @array t a list-like table
691
-- @func cmp a function that defines equality (otherwise uses ==)
692
-- @return a map-like table
693
-- @see seq.count_map
694
function tablex.count_map (t,cmp)
665✔
695
    assert_arg_indexable(1,t)
19✔
696
    local res,mask = {},{}
19✔
697
    cmp = function_arg(2,cmp or '==')
24✔
698
    local n = #t
19✔
699
    for i = 1,#t do
95✔
700
        local v = t[i]
76✔
701
        if not mask[v] then
76✔
702
            mask[v] = true
57✔
703
            -- check this value against all other values
704
            res[v] = 1  -- there's at least one instance
57✔
705
            for j = i+1,n do
152✔
706
                local w = t[j]
95✔
707
                local ok = cmp(v,w)
95✔
708
                if ok then
95✔
709
                    res[v] = res[v] + 1
19✔
710
                    mask[w] = true
19✔
711
                end
712
            end
713
        end
714
    end
715
    return makemap(res)
19✔
716
end
717

718
--- filter an array's values using a predicate function
719
-- @within MappingAndFiltering
720
-- @array t a list-like table
721
-- @func pred a boolean function
722
-- @param arg optional argument to be passed as second argument of the predicate
723
function tablex.filter (t,pred,arg)
665✔
724
    assert_arg_indexable(1,t)
57✔
725
    pred = function_arg(2,pred)
72✔
726
    local res,k = {},1
57✔
727
    for i = 1,#t do
817✔
728
        local v = t[i]
760✔
729
        if pred(v,arg) then
960✔
730
            res[k] = v
722✔
731
            k = k + 1
722✔
732
        end
733
    end
734
    return setmeta(res,t,'List')
57✔
735
end
736

737
--- return a table where each element is a table of the ith values of an arbitrary
738
-- number of tables. It is equivalent to a matrix transpose.
739
-- @within Merging
740
-- @usage zip({10,20,30},{100,200,300}) is {{10,100},{20,200},{30,300}}
741
-- @array ... arrays to be zipped
742
function tablex.zip(...)
665✔
743
    return tablex.mapn(function(...) return {...} end,...)
76✔
744
end
745

746
local _copy
747
function _copy (dest,src,idest,isrc,nsrc,clean_tail)
560✔
748
    idest = idest or 1
190✔
749
    isrc = isrc or 1
190✔
750
    local iend
751
    if not nsrc then
190✔
752
        nsrc = #src
95✔
753
        iend = #src
95✔
754
    else
755
        iend = isrc + min(nsrc-1,#src-isrc)
95✔
756
    end
757
    if dest == src then -- special case
190✔
758
        if idest > isrc and iend >= idest then -- overlapping ranges
19✔
759
            src = tablex.sub(src,isrc,nsrc)
24✔
760
            isrc = 1; iend = #src
19✔
761
        end
762
    end
763
    for i = isrc,iend do
551✔
764
        dest[idest] = src[i]
361✔
765
        idest = idest + 1
361✔
766
    end
767
    if clean_tail then
190✔
768
        tablex.clear(dest,idest)
76✔
769
    end
770
    return dest
190✔
771
end
772

773
--- copy an array into another one, clearing `dest` after `idest+nsrc`, if necessary.
774
-- @within Copying
775
-- @array dest a list-like table
776
-- @array src a list-like table
777
-- @int[opt=1] idest where to start copying values into destination
778
-- @int[opt=1] isrc where to start copying values from source
779
-- @int[opt=#src] nsrc number of elements to copy from source
780
function tablex.icopy (dest,src,idest,isrc,nsrc)
665✔
781
    assert_arg_indexable(1,dest)
76✔
782
    assert_arg_indexable(2,src)
76✔
783
    return _copy(dest,src,idest,isrc,nsrc,true)
76✔
784
end
785

786
--- copy an array into another one.
787
-- @within Copying
788
-- @array dest a list-like table
789
-- @array src a list-like table
790
-- @int[opt=1] idest where to start copying values into destination
791
-- @int[opt=1] isrc where to start copying values from source
792
-- @int[opt=#src] nsrc number of elements to copy from source
793
function tablex.move (dest,src,idest,isrc,nsrc)
665✔
794
    assert_arg_indexable(1,dest)
114✔
795
    assert_arg_indexable(2,src)
114✔
796
    return _copy(dest,src,idest,isrc,nsrc,false)
114✔
797
end
798

799
function tablex._normalize_slice(self,first,last)
665✔
800
  local sz = #self
190✔
801
  if not first then first=1 end
190✔
802
  if first<0 then first=sz+first+1 end
190✔
803
  -- make the range _inclusive_!
804
  if not last then last=sz end
190✔
805
  if last < 0 then last=sz+1+last end
190✔
806
  return first,last
190✔
807
end
808

809
--- Extract a range from a table, like  'string.sub'.
810
-- If first or last are negative then they are relative to the end of the list
811
-- eg. sub(t,-2) gives last 2 entries in a list, and
812
-- sub(t,-4,-2) gives from -4th to -2nd
813
-- @within Extraction
814
-- @array t a list-like table
815
-- @int first An index
816
-- @int last An index
817
-- @return a new List
818
function tablex.sub(t,first,last)
665✔
819
    assert_arg_indexable(1,t)
152✔
820
    first,last = tablex._normalize_slice(t,first,last)
192✔
821
    local res={}
152✔
822
    for i=first,last do append(res,t[i]) end
528✔
823
    return setmeta(res,t,'List')
152✔
824
end
825

826
--- set an array range to a value. If it's a function we use the result
827
-- of applying it to the indices.
828
-- @array t a list-like table
829
-- @param val a value
830
-- @int[opt=1] i1 start range
831
-- @int[opt=#t] i2 end range
832
function tablex.set (t,val,i1,i2)
665✔
833
    assert_arg_indexable(1,t)
114✔
834
    i1,i2 = i1 or 1,i2 or #t
114✔
835
    if types.is_callable(val) then
144✔
836
        for i = i1,i2 do
152✔
837
            t[i] = val(i)
144✔
838
        end
839
    else
840
        for i = i1,i2 do
247✔
841
            t[i] = val
171✔
842
        end
843
    end
844
end
845

846
--- create a new array of specified size with initial value.
847
-- @int n size
848
-- @param val initial value (can be `nil`, but don't expect `#` to work!)
849
-- @return the table
850
function tablex.new (n,val)
665✔
851
    local res = {}
19✔
852
    tablex.set(res,val,1,n)
19✔
853
    return res
19✔
854
end
855

856
--- clear out the contents of a table.
857
-- @array t a list
858
-- @param istart optional start position
859
function tablex.clear(t,istart)
665✔
860
    istart = istart or 1
76✔
861
    for i = istart,#t do remove(t) end
396✔
862
end
863

864
--- insert values into a table.
865
-- similar to `table.insert` but inserts values from given table `values`,
866
-- not the object itself, into table `t` at position `pos`.
867
-- @within Copying
868
-- @array t the list
869
-- @int[opt] position (default is at end)
870
-- @array values
871
function tablex.insertvalues(t, ...)
665✔
872
    assert_arg(1,t,'table')
76✔
873
    local pos, values
874
    if select('#', ...) == 1 then
76✔
875
        pos,values = #t+1, ...
38✔
876
    else
877
        pos,values = ...
38✔
878
    end
879
    if #values > 0 then
76✔
880
        for i=#t,pos,-1 do
285✔
881
            t[i+#values] = t[i]
209✔
882
        end
883
        local offset = 1 - pos
76✔
884
        for i=pos,pos+#values-1 do
532✔
885
            t[i] = values[i + offset]
456✔
886
        end
887
    end
888
    return t
76✔
889
end
890

891
--- remove a range of values from a table.
892
-- End of range may be negative.
893
-- @array t a list-like table
894
-- @int i1 start index
895
-- @int i2 end index
896
-- @return the table
897
function tablex.removevalues (t,i1,i2)
665✔
898
    assert_arg(1,t,'table')
19✔
899
    i1,i2 = tablex._normalize_slice(t,i1,i2)
24✔
900
    for i = i1,i2 do
57✔
901
        remove(t,i1)
38✔
902
    end
903
    return t
19✔
904
end
905

906
local _find
907
_find = function (t,value,tables)
908
    for k,v in pairs(t) do
508✔
909
        if v == value then return k end
315✔
910
    end
911
    for k,v in pairs(t) do
367✔
912
        if not tables[v] and type(v) == 'table' then
250✔
913
            tables[v] = true
174✔
914
            local res = _find(v,value,tables)
174✔
915
            if res then
174✔
916
                res = tostring(res)
76✔
917
                if type(k) ~= 'string' then
76✔
918
                    return '['..k..']'..res
×
919
                else
920
                    return k..'.'..res
76✔
921
                end
922
            end
923
        end
924
    end
925
end
926

927
--- find a value in a table by recursive search.
928
-- @within Finding
929
-- @tab t the table
930
-- @param value the value
931
-- @array[opt] exclude any tables to avoid searching
932
-- @return a fieldspec, e.g. 'a.b' or 'math.sin'
933
-- @usage search(_G,math.sin,{package.path}) == 'math.sin'
934
function tablex.search (t,value,exclude)
665✔
935
    assert_arg_iterable(1,t)
57✔
936
    local tables = {[t]=true}
57✔
937
    if exclude then
57✔
938
        for _,v in pairs(exclude) do tables[v] = true end
38✔
939
    end
940
    return _find(t,value,tables)
57✔
941
end
942

943
--- return an iterator to a table sorted by its keys
944
-- @within Iterating
945
-- @tab t the table
946
-- @func f an optional comparison function (f(x,y) is true if x < y)
947
-- @usage for k,v in tablex.sort(t) do print(k,v) end
948
-- @return an iterator to traverse elements sorted by the keys
949
function tablex.sort(t,f)
665✔
950
    local keys = {}
19✔
951
    for k in pairs(t) do keys[#keys + 1] = k end
209✔
952
    tsort(keys,f)
19✔
953
    local i = 0
19✔
954
    return function()
955
        i = i + 1
209✔
956
        return keys[i], t[keys[i]]
209✔
957
    end
958
end
959

960
--- return an iterator to a table sorted by its values
961
-- @within Iterating
962
-- @tab t the table
963
-- @func f an optional comparison function (f(x,y) is true if x < y)
964
-- @usage for k,v in tablex.sortv(t) do print(k,v) end
965
-- @return an iterator to traverse elements sorted by the values
966
function tablex.sortv(t,f)
665✔
967
    f = function_arg(2, f or '<')
24✔
968
    local keys = {}
19✔
969
    for k in pairs(t) do keys[#keys + 1] = k end
209✔
970
    tsort(keys,function(x, y) return f(t[x], t[y]) end)
541✔
971
    local i = 0
19✔
972
    return function()
973
        i = i + 1
209✔
974
        return keys[i], t[keys[i]]
209✔
975
    end
976
end
977

978
--- modifies a table to be read only.
979
-- This only offers weak protection. Tables can still be modified with
980
-- `table.insert` and `rawset`.
981
--
982
-- *NOTE*: for Lua 5.1 length, pairs and ipairs will not work, since the
983
-- equivalent metamethods are only available in Lua 5.2 and newer.
984
-- @tab t the table
985
-- @return the table read only (a proxy).
986
function tablex.readonly(t)
665✔
987
    local mt = {
19✔
988
        __index=t,
19✔
989
        __newindex=function(t, k, v) error("Attempt to modify read-only table", 2) end,
38✔
990
        __pairs=function() return pairs(t) end,
30✔
991
        __ipairs=function() return ipairs(t) end,
24✔
992
        __len=function() return #t end,
30✔
993
        __metatable=false
14✔
994
    }
995
    return setmetatable({}, mt)
19✔
996
end
997

998
return tablex
665✔
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc