Is there a table decoder in Lua?

1

I'm wondering why I want to know if one table is the same as another, whether it's an empty table or something else.

    
asked by anonymous 23.07.2017 / 23:42

1 answer

0

Table of contents?

A table is empty if next(t) == nil , or if tamanhoDaArray <= 0 or tamanhoDaArray == 0 .

Comparing tables (x = y)

There are several different ways to check if one table is the same as another.

I suppose you already know that a table is both array of values and dictionary with key pairs and values (a.k.a. hash). An array is always guaranteed to be more efficient than a hash (even optimized). Hash fields are only needed in rare and dynamic cases (in which there is no use for Inline Caching optimization in field access).

The comparison you want depends on the structure of the x and y tables. Luiz's comment leads you to a simple and efficient comparison of tables, completely, deepcompare . Below are a few examples¹ for comparing arrays only.

[1] : rawget and rawset can be used instead of t[k] and t[k] = v , if there is no metatable.

>

1) Comparing arrays superficially

local function CompareArraySurface(x, y)
    local xl = #x;
    if xl ~= #y then return false; end

    for i = 1, #x do
        if x[i] ~= y[i] then
            return false;
        end
    end

    return true;
end

local print = (_ENV or _G).print;

print(
    CompareArraySurface({}, { 0, 0, 0 })          --> false,
  , CompareArraySurface({ 4, 1, 3 }, { 4, 1, 3 }) --  true,
  , CompareArraySurface({ { 1 } }, { { 1 } })     --  false
);

2) Comparing multi-dimensional arrays

local CompareDims;

function CompareDims(x, y, dim)
    if dim <= 0 then
        return x == y;
    end

    local xl = #x;
    if xl ~= #y then return false; end

    for i = 1, xl do
        if not CompareDims(x[i], y[i], dim - 1) then
            return false;
        end
    end

    return true;
end

print(
  -- Array bidimensional (2 dimensões)
    CompareDims({ { 5 } }, { { 5 } }, 2) --> true,

  -- Array unidimensional (1 dimensão)
  , CompareDims({ { 5 } }, { { 5 } }, 1) -->  false
);
    
27.07.2017 / 14:08