Is there a table breaker in Lua?

Asked

Viewed 142 times

1

I’m wondering this because I want to know if one table is the same as another, if it’s an empty table or something.

  • What is a table decoder?

  • 1

    A table t is empty if next(t)==nil.

  • 1

    For table comparison see http://lua-users.org/lists/lua-l/2014-09/msg00421.html.

  • Let me see if I understand: you want to know if an index already exists or it is still empty, that is, if that item has already been inserted in the table or already exists is this ?

1 answer

0

Table vázia?

A table is varied 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 equal to another.

I suppose you already know that a table is so much array of how much value 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 the optimization technique does not help "Inline Caching" in field access).

The comparison you want depends on the structure of the tables x and y. Luiz’s comment leads you to a simple and efficient comparison of tables, in full, deepcompare. Below I leave some examples¹ to compare arrays only.

[1]: can be used rawget and rawset 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
);

Browser other questions tagged

You are not signed in. Login or sign up in order to post.