Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
1

How to search dictionarys?

Asked by 7 years ago
Edited 7 years ago

Hi there,

Currently I have a dictionary in my code to work a question-answer system.

I am trying to find if the user entered the right answer, and for a bonus round, the right question [something easy and have multiple answers].

I need some way to view the answer of a dictionary.

My code:


qa= {["Question"] = "Answer"} function searcht(table, word) for i = 1,#table do if table[i] == word then return table[i] else return nil end end end searcht(qa, "Question")`

Any help would be apprechiated!

Thanks.

1 answer

Log in to vote
1
Answered by
movsb 242 Moderation Voter
7 years ago

Use pairs

pairs is an iterator factory that returns next, which is a primitive function in Lua that returns the next index and value inside of a table, array, or dictionary.

Here is an example of how you use pairs:

local qa = {
     ["Question"] = "Answer"

}

function searcht(table, word)
    for i,v in pairs(table) do 
        if v == word then 
            return v
        else 
            return nil 
        end 
    end 
end
searcht(qa, "Question")

i is a variable for the current index of the table (an example of an index of your table would be ["Question"]), and v is a variable for the current value of the table (i.e. "Answer")

I hope this helped you.

0
Thanks a bunch! AdministratorReece 193 — 7y
Ad

Answer this question