'Find record in another table

How can I search for my table set in the t table?

my =   { type = 'device' , id = 358}
t = {{type = 'device' , id = 358}, {type = 'device' , id = 3}}


Solution 1:[1]

You can implement a simple linear search:

for index, element in ipairs(t) do
    if element.type == t.type and element.id == t.id then
        -- do something using the index / element
        break
    end
end

if you want to speed things up, you can create a lookup table by ID - if the IDs are unique, you don't even need to check the types:

devices_by_id = {}
for _, device in ipairs(t) do
    devices_by_id[device.id] = device
end

then you can trivially obtain elements by ID using devices_by_id[my_device.id], which will be much faster than the linear search; creating the index however will be about as fast as the linear search.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 LMD