I’d like to get a random tuple from a table with math.random to make the player vote between 2 options and what gets voted for most happens but it keeps returning an error
Here is the code where i believe the problem lies:
local Candidates = {
["Candidate1"] = {
["Text"] = "Grow",
["Function"] = function()
print("Grow")
end,
},
["Candidate2"] = {
["Text"] = "Shrink",
["Function"] = function()
print("Shrink")
end
}
}
function Mod.GetCandidate()
local Candidate = Candidates[math.random(1, table.maxn(Candidates))]
return Candidate
end
I have tried using select and maxn but both retuned 0 so now i have no clue what to do
this script is in a module script but i am confident that i found the mistake here because the error comes up on the module so im assuming the problem is on the module side
In your case, you’re using the table as a dictionary with key-value pairs, so table.maxn and # will always return 0.
What I’d do to get a random entry from the table would be to do something like this:
local Keys = {}
for Key, _ in Candidates do
table.insert(Keys, Key)
end
local CandidateKey = Keys[math.random(1, #Keys)]
local RandomCandidate = Candidates[CandidateKey]