How to deep search a table

Hey guys.

So I am currently making a script that deep-searches a dictionary/“deep table”, and I stumbled across this post.

The post:

Although the script @sjr04 gave worked, he did not give any explanation. Whilst I have grasped the essence of a recursive function, I have some problems understanding how it loops through. The current script I got:

dict = {
        ["Wizards"] = {"Player1, Player2"};
        ["Trolls"] = {"Player3"};
        ["Witch"] = {};
        ["Monster"] = {"Player4"};

        }

 local function recursive_find(t, key_to_find)
    for key, value in pairs(t) do
        if value == key_to_find then
            return true
        end

        if typeof(value) == "table" then
            return recursive_find(value, key_to_find)
        end
    end
    return false
end

print(recursive_find(dict, "Player4")) -- true, if it finds. 

So, I have found out so far, that it searched through the main “arrays”, so

wizards
trolls
witch
monster

But after the first if statement, it calls the function again WITHIN the function.

And that makes we wonder, that only the first table get’s searched, but then again, it does search trough the whole. I just dont understand, does is run the function multiple times simultaneously? Thanks!

If you just have a video that explains how the code get’s read, that would be great! Thanks guys!

local function recursive_find(t, key_to_find)
    for key, value in pairs(t) do
        if value == key_to_find then
            return true
        end

So the for key, value in pairs loob searches through the table that you give it, in this example it is dict.
The if statement checks to see if the value is the key that you are looking for, for example if you were looking for “Trolls” it will return true.

        if typeof(value) == "table" then
            return recursive_find(value, key_to_find)
        end
    end
    return false
end

print(recursive_find(dict, "Player4")) -- true, if it finds. 

The typeof if statement checks whether or not the value inside the original table is also a table and if it is it will return the function recursive_find. and it will just loop through that table and if there is a table inside of that table it goes on.

3 Likes

So, in a way, multiple «versions» of the loop/function run at the same time. Kinda, like it loops through the main, but at the same time also the children of the loop. Right?

No I dont think so, I believe it loops through the first table, then when its done if there are tables inside of the first table it will loop through that one.

OOOoOoOOoOooOoh.

Noooow I understood. Thank you so much!

1 Like