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

How do I pick a dictionary table from a Dictionary?

local Dict = {
    Quote1 = {
        Text = "What's up";
        Color = BrickColor.new("Lime green").Color
        };
    Quote2 = {
        Text = "yoooooo";
        Color = BrickColor.new("Lapis").Color
        }
    }
while wait(1) do
	math.randomseed(os.time())
	local randomQuote = Dict[math.random(1, #Dict)] -- i get an error here
	print(randomQuote) 
end

error: Players.creeperhunter76.PlayerScripts.command:21: bad argument #2 to 'random' (interval is empty)

3 comments

1

Dictionaries dont work with the # system to get the number of keys.

0

Why do you want to use a dictionary in the first place? Judging from how you're using it, It seems like an array would do you fine.

0

Good point. I don't really like dictionaries because I have to make sure I spell my keys right.

1 answer

✓ Accepted answer

As hiimgoodpack says, "#" doesn't work on dictionaries because it only counts array elements.

One option is to manually count the keys and select a random one based on that, like this function does:

function PickRandomKeyFromDict(d)
	local n = 0
	for _, _ in pairs(d) do
		n = n + 1
	end
	n = n - math.random(1, n)
	for k, _ in pairs(d) do
		if n == 0 then return k end
		n = n - 1
	end
end

You could use it like this:

local quoteKey = PickRandomKeyFromDict(Dict)
local quoteValue = Dict[quoteKey]
--can now do quoteValue.Text and quoteValue.Color

However, you probably don't need quoteKey and could have all this work better as a list:

local quotes = {
	{Text = "What's up", Color = BrickColor.new("Lime green").Color},
	{Text = ""yoooooo", Color = BrickColor.new("Lapis").Color},
	--etc
}
--Get random quote by doing:
local quote = quotes[math.random(1, #quotes)]
--can now do quote.Text and quote.Color

In either case, don't forget to initialize the randomseed at the top of your script: math.randomseed(tick()); math.random() (you need to skip the first math.random for superior results). You're only supposed to initialize the randomseed once, not multiple times in a loop. (There do exist reasons for initializing it multiple times, but in your case once is better so that you can get a new quote whenever you want and it will still seem random.)

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