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
}
local dictionaryIndex = {"Q", "E", "R", "T"}
local function findLength(dictionary)
total = 0
for i,v in pairs (keyDictionary) do
total = total+1
end
return total
end
local function findRandomIndex()
local index = dictionaryIndex[math.random(findLength(keyDictionary))]
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. :)
2 comments
Ohh, alright i think i got it now. Thanks for the help! :)
If i have any questions i'll let you know