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:

01qa= {["Question"] = "Answer"}
02 
03    function searcht(table, word)
04 
05    for i = 1,#table do
06 
07                        if table[i] == word then
08                            return table[i]
09 
10                            else
11 
12                            return nil
13 
14                            end
15 
16                        end
17    end
18 
19    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:

01local qa = {
02     ["Question"] = "Answer"
03 
04}
05 
06function searcht(table, word)
07    for i,v in pairs(table) do
08        if v == word then
09            return v
10        else
11            return nil
12        end
13    end
14end
15searcht(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