I have created a dictionary for my quotes but I’m going to use math.random to get a random quote and change the GUI text labels to the texts accordingly. How do I do this? (its for a plugin btw)
Code
--Quotes Dictionary
local Quotes = {
{"Nelson Mandela","Money won't create success, the freedom to make it will"},
{"Nelson Mandela","It always seems impossible until it's done"},
}
You can’t directly index using math.random because it’s a dictionary. You’ll need to turn it into an array.
Also, you can’t have two items in a dictionary with the same key. You can’t have ["-Nelson Mandela"] twice.
Option 1: Just make it an array.
--Quotes Array
local Quotes = {
{"-Nelson Mandela", "It always seems impossible until it's done"},
{"-Nelson Mandela", "Money won't create success, the freedom to make it will"},
}
-- Choose random quote
local randomQuoteInfo = Quotes[math.random(1, #Quotes)]
print("Quote: "..randomQuoteInfo[2].." "..randomQuoteInfo[1])
-- Quote: It always seems impossible until it's done -Nelson Mandela
It looks like this is the best option for you since you’re trying to have two items with the same key. You can’t do that, so you’ll have to use an array if you want two to have the same author.
Option 2: Programmatically generate an array.
--Quotes Dictionary
local Quotes = {
["-Nelson Mandela"] = "It always seems impossible until it's done",
["-Nelson Mandela"] = "Money won't create success, the freedom to make it will",
}
-- Create array
local QuotesArray = {}
for key, value in pairs(Quotes) do
table.insert(QuotesArray, {key, value})
end
-- Choose random quote
local randomQuoteInfo = QuotesArray[math.random(1, #QuotesArray)]
print("Quote: "..randomQuoteInfo[2].." "..randomQuoteInfo[1])
-- Quote: It always seems impossible until it's done -Nelson Mandela
Also, please don’t add emoticons to your title. Arguably just my opinion, but it makes the forums seem a bit unprofessional.