Quirrel4.41.0

deduplicate_object

Global, available without an import
deduplicate_object(obj: table|array|null): table|array|null

Walks obj and merges equal tables and arrays it finds inside.

examples/globals/deduplicate_object-basic.nut
let team = {alpha = [1, 2], bravo = [1, 2]}   // two separate but equal arrays
deduplicate_object(team)

println("team.alpha == team.bravo =", team.alpha == team.bravo)  // merged into one
Output:
team.alpha == team.bravo = true

Parameters

objtable|array|nulltable, array, or null to walk

Return value

Always null, for any obj. The call does its work in place and returns no result.

Errors

None. obj outside table, array or null fails the signature's own type check before the body runs.

Notes

Every table and array reachable from obj - its values, and their values, and so on - is marked immutable, the same flag freeze sets. Two of them get merged into one shared instance when they are equal, hold at most 20 items, and every value in them is null, bool, int, float or string; a smaller memory footprint is the purpose of the call.

The mark lands on what obj holds, not on obj itself: getobjflags(obj) right after the call is unchanged. Keep using the same variable; the call does not return a frozen replacement.

Example

examples/globals/deduplicate_object.nut
let t = {a = [1, 2], b = [1, 2]}   // two separate but equal arrays
println("deduplicate_object(t) =", deduplicate_object(t))       // the call itself always evaluates to null

println("t.a == t.b =", t.a == t.b)        // the equal sub-arrays were merged into one
println("getobjflags(t.a) =", getobjflags(t.a))  // the merged array is now immutable
println("getobjflags(t) =", getobjflags(t))    // the outer table itself is left as it was

try { t.a.append(3) } catch (e) { println("t.a.append(3) throws:", e) }
Output:
deduplicate_object(t) = null
t.a == t.b = true
getobjflags(t.a) = 1
getobjflags(t) = 0
t.a.append(3) throws: Cannot modify immutable object

See also

freezeReturns a reference to obj with the immutable flag set.
getobjflagsReturns the engine flag bits stored on obj's reference.
globalsmodule index