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