Search code examples
lua

Search for an item in multiple Lua lists


I'm working on a script right now and have encountered a roadblock where I can't quite figure out how to check if a value is in any of the selected tables in Lua.

Example script of the problem below.

players = {213, 644}
helpers = {632, 965}

-- How would I check if a number (for example 632) was in either of these two tables?

Solution

  • Use this simple table find value _v:

    local players = {213, 644}
    local helpers = {632, 965}
    
    local function find(t, _v)
        for i, v in pairs(t) do
            local type1 = type(v)
            if type1 == 'table' then
                local value = { find(v, _v) }
                if #value ~= 0 then
                    table.insert(value, 2, i)
                    return unpack(value)
                end
            elseif i == _v or v == _v then
                return i, v
            end
        end
    end
    
    -- Example:
    print(find(players, 632) and 'Was finded in table: players') -- nil
    print(find(helpers, 632) and 'Was finded in table: helpers') -- 'Was finded...'