Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
✓ ANSWER ACCEPTED

How to search dictionarys?

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

✓ Accepted answer

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.

1 comment

0

Thanks a bunch!

This discussion is preserved as it was. New answers, comments, and votes are closed.