Hesoyam
Hesoyam

Reputation: 1

Find value in LUA tables

I have 3 tables in lua g1, g2, g3 and I'm looking for an efficient way to quickly find which table a number (ID) is in

This is what I have so far and it seems inefficiently slow.

g1 = {
    37863,
    78372,
    ...
    ...
}
g2 = {
    19599,
    84651,
    ...
    ...
}
g3 = {
    37462,
    42843,
    ...
    ...
}
for i = 1, 170000 do
    if (g1[i] == ID) then
        --number found in G1
        break
    elseif (g2[i] == ID) then
        --number found in G2
        break
    elseif (g3[i] == ID) then
        --number found in G3
        break
    end
end

what I can think of is that I could reconstruct the tables, instead of putting the number after g table get it directly into the table like this:

g = {
    [37863] = 3,
    [78372] = 2,
    [18788] = 1,
}
if (g[ID] == 1) then
 --number found in G1
elseif (g[ID] == 2) then
 --number found in G2
elseif (g[ID] == 3) then
 --number found in G3
end

what you think might be most effective

Upvotes: 0

Views: 1037

Answers (2)

Corotyest
Corotyest

Reputation: 31

If you want to collect a specific value you can simple iter the table where you want to search, I can give you a function explaining you the chuncks.

local function find(table, value)
    for key, _value in pairs(table) do
        if type(_value) == 'table' then
            local f = { find(_value, value) }
            if #f ~= 0 then
                table.insert(f, 2, key); return unpack(f)
            end
        elseif _value == value or key == value then
            return key, _value
        end
    end
end

First you do is create the function, and iter it. Scaning all sub-tables may the main table have, if the value: value is found return the path to get the value else return nothing.

Or for friends: if the function return something the value is in it or in some sub-table.

I hope this result useful to you, great day!

Upvotes: 0

Paul Kulchenko
Paul Kulchenko

Reputation: 26794

It should be easy for you to test on your tables, which is what you should do anyway, but in a general case the second option is going to be much faster on large tables for random access. If you do always need to go through the entire list and split it into three buckets, then the first option can be faster and that's why you need to test it on your specific use case.

Upvotes: 1

Related Questions