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

How do I pick a dictionary table from a Dictionary?

Asked by 6 years ago
Edited 6 years ago
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)

1
Dictionaries dont work with the # system to get the number of keys. hiimgoodpack 2009 — 6y
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. XAXA 1569 — 6y
0
Good point. I don't really like dictionaries because I have to make sure I spell my keys right. hiimgoodpack 2009 — 6y

1 answer

Log in to vote
0
Answered by 6 years ago

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.)

Ad

Answer this question