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:
01 | qa = { [ "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.
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:
01 | local qa = { |
02 | [ "Question" ] = "Answer" |
03 |
04 | } |
05 |
06 | function 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 |
14 | end |
15 | 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.