--//Dictionary local keyDictionary = { ["Q"] = false , ["E"] = false , ["R"] = false , ["T"] = false } for i = 1, math.random(keyDictionary) do print(math.random(keyDictionary)) end
I had help earlier on, but i still don't get it since this is my first time using tables/dictionary. But i'm just confused with for example : printing either 'Q, E, R or T' if picked and prints again if its true or false.
When you create a dictionary, you're essentially changing the index from integers (1, 2, 3) to strings or other values that Lua allows ("Apple", "Banana", "Cherry").
As for your script, there are a few problems.
math.random(), requires an integer value. keyDictionary is clearly a Dictionary value so that won't work with that function.
So it seems you were trying to print the index of the table with your print statement. If you used math.random() correctly, that would still only print an integer and would not have provided the results you wanted.
Another problem that may have happened is you trying to index the Dictionary with an integer. An example:
keyDictionary[math.random(1, 4)]
This would not have found the value you wanted, since as I said before, the indexes are now strings ("Q", "E", etc), not integers (1, 2, 3, etc).
Now I'll explain a way to complete the task that you intended to complete.
local keyDictionary = { ["Q"] = false, ["E"] = false, ["R"] = false, ["T"] = false } -- Dictionary Created local dictionaryIndex = {"Q", "E", "R", "T"} -- I recommend a function to create this table, rather hard coding it --[[ The length of a dictionary cannot be found with the # operator, so we'll use a function to find the length ]]-- local function findLength(dictionary) total = 0 for i,v in pairs (keyDictionary) do total = total+1 end return total end --[[ Now that we have the amount of values, we can now use it to find a random value to find our index ]]-- local function findRandomIndex() local index = dictionaryIndex[math.random(findLength(keyDictionary))] -- We have our index, now to find the value in our dictionary. local value = keyDictionary[index] return index,value end
And there you are. This script returns a random index and the corresponding values. There may be a more efficient way in doing this, unsure if there is a shortcut in finding the length of dictionaries, but regardless, this should help your understanding of dictionaries.
If you have any questions, please feel free to ask. :)