Need help with tables and math.random

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

those don’t work with dictionaries (nor does #)

it feels like there HAS to be a better way of doing this but you can count the number of elements by running it through a pairs loop

local count = 0
for _,_ in target_array do
    count += 1
end

that’s what i always do and its good enough for me :+1:

also you wont be able to access it like this since its stored as Candidate1, Candidate2, etc;
you’d have to do

Candidates["Candidate"..math.random(1, lengthOfCandidates)]

i did that but for some reason the random factor just returns nil without error

Both table.maxn and # assume the table is an array with numbered indices like the following

local Candidates = {
    {
        ["Text"] = "Grow",
        ["Function"] = function()
            print("Grow")
        end,
    },
	
    {
        ["Text"] = "Shrink",
        ["Function"] = function()
            print("Shrink")
        end
    }
}

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]

Edit: Basically the same as what @PuffoThePufferfish suggests

i edited the post, @Uhsleep91’s method will also work but both are O(n) so its just kinda ur preference

YEEEEEEEEEE IT WORKS

thanks to the both of you i actually didnt think you could do it like that

(this will benefit futute generations to come)

1 Like

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.