How would I print a random value from this modulescript
local Cards = {
Card_1 = "Explode.",
Card_2 = "Dance."
}
return Cards
How would I print a random value from this modulescript
local Cards = {
Card_1 = "Explode.",
Card_2 = "Dance."
}
return Cards
You could copy the dictionary as an array, then chose a random value from there:
local Cards = {
Card_1 = "Explode.",
Card_2 = "Dance."
}
--converts a dictionary to an array
function toArray(dictionary)
local result = {}
--do not use ipairs
for _, v in pairs(dictionary) do
table.insert(result, v)
end
return result
end
local array = toArray(Cards)
local index = math.random(1, #array)
local chosen = array[index]
print(chosen)
local function GetTableSize(t)
local a = 0
for i,v in pairs(t) do
a += 1
end
return a
end
local function GetRandValue(t)
local rand = math.random(GetTableSize(t))
local a = 0
for i, v in pairs(t) do
a += 1
if i == rand then
return v
end
end
end
or just a lot simplier and performant do what @NyrionDev mentioned
Or
Just make the table an array
local Cards = {
[1] = "Explode.",
[2] = "Dance."
}
Use this:
CardsDictionary = {
Card_1 = "Explode.",
Card_2 = "Dance."
}
CardsTable = {
"Card_1",
"Card_2",
}
local randomCard = CardsDictionary[CardsTable[math.random(1, #CardsTable)]]
print(randomCard)
You could use math.random
to select a random value out of the table as the ModuleScript returns a table that can be used in other scripts. However, due to the structure of your module, you’ll need to use a method to change your dictionary into an array, as @NyrionDev mentioned.
A simple method from the solution to this ScriptingHelpers post can be seen below:
---> services
local ServerScriptService = game:GetService("ServerScriptService")
---> const
local cardsModule = require(ServerScriptService:WaitForChild("CardsModule")) -- change to the path of your module
-- change dictionary into array
local cards = {}
for card,_ in pairs(cardsModule) do
table.insert(cards,card)
end
local randomCard = cards[math.random(1,#cards)]
print(randomCard)
The solution to this post may also be useful to you:
Usually randomized values should use arrays. Your setup there can use some improvement:
local Cards = { -- This is now an array
{
CardNumber = "Card_1",
Name = "Explode",
},
{
CardNumber = "Card_1",
Name = "Explode",
},
}
local randomCard = Cards[math.random(1, #Cards)] -- Picks a random card from the array
Try to avoid dictionaries if you don’t need them.