I am using a dictionary because I am using the keys in the dictionary so that I know a certain dialogue option corresponds to a type of item. I want to have the VALUES (NOT THE KEYS) of the array/dictionary to be picked at random but I keep getting an error saying " 'random' (interval is empty) "
Here is my code
local initialPrompts = { ["osv"] = "Hello there, one scoop of vanilla please.", ["osv"] = "Let me have one scoop of vanilla ice cream.", ["osc"] = "I'd like one scoop of chocolate ice cream." } local choicePrompts = {"Thanks", "Thank You", "Have a nice day", "Enjoy your day"} local dialog = script.Parent.Brain.Dialog local iceCreamChoice = script.Parent.icecreamchoice enabled = true if enabled == true then enabled = false math.randomseed(tick()) local chosenInitialPrompt = initialPrompts[math.random(1,#initialPrompts)] print(chosenInitialPrompt) enabled = true end
Careful: what you have written is not a valid dictionary. You cannot repeat keys. Lua will pick either the first "osv"
or the secodn "osv"
and use just one.
You can't use #
on a dictionary. #
tells how to find numeric indices, 1, 2, 3, ..., #list
. But a dictionary has nothing at those indices.
Since math.random
returns a number, you're not going to find anything if you try initialPrompts[math.random(...)]
anyway.
The only random functionality in Lua is math.random()
which is used to produce numbers.
A straightforward way to use math.random
to get something other than numbers is to pick objects by their (numeric) index in a list:
function chooseFromList(list) return list[math.random(#list)] end
A dictionary is not a list. But from a dictionary we can make lists. We could make a list of the keys, pick a random key, then get the value at that key. Or we could just make a list of values, and pick a value.
local keys = {} for key in pairs(dictionary) do table.insert(keys, key) end local randomKey = chooseFromList(keys) local randomValue = dictionary[randomKey]