Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
1

How to randomize a dictionary?

Asked by
Seyfert 90
7 years ago
Edited 7 years ago

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
0
'math.random(a, b)' will throw that error if there is no integer between the range 'a-b', where both 'a' and 'b' are inclusive. By the way, you can omit '1' if you want 'math.random' to give a random value between '1' and some other number. Link150 1355 — 7y

1 answer

Log in to vote
3
Answered by
BlueTaslem 18071 Moderation Voter Administrator Community Moderator Super Administrator
7 years ago
Edited 7 years ago

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]
Ad

Answer this question