Why isn't this name picker working?

Hi DevForum,

I tried making a name picking script, where it randomly picks a name from the table and prints it, however it isn’t working when I call the function on the server script, and just prints “nil”. Can anyone seem to help with this? Thanks!

local namesmodule = {}

function namesmodule.pickName()
	local names = {
		["Bob"] = 1;
		["Dan"] = 1;
		["Landyn"] = 1;
		["Julian"] = 1;
		["Matthew"] = 1; 
		["Robert"] = 1;
		["Cam"] = 1;
		["Kyle"] = 1;
		["Jamal"] = 1;
		["Tyrone"] = 1;
		["Mac"] = 1;
		["Jonathan"] = 1;
		["Julia"] = 2;
		["Max"] = 1;
		["Sammy"] = 2;
		["Kelly"] = 2;
		["Emily"] = 2;
		["Madison"] = 2;
		["Samantha"] = 2;
		["Melly"] = 2;
		["Ryan"] = 1;
		["Connor"] = 1;
		["Zack"] = 1;
		["Joclien"] = 2;
		["Candice"] = 2;
		["Cadence"] = 2;
		["Britney"] = 2;
		["Delany"] = 2;
		["James"] = 1;
		["John"] = 1;
		["Micheal"] = 1;
		["Patricia"] = 2;
		["Jennifer"] = 2;
		["Linda"] = 2;
		["Barbra"] = 2;
		["Sarah"] = 2;
		["Charles"] = 1;
		["Nancy"] = 2;
		["Karen"] = 2;
		["Pablo"] = 1;
		["Kevin"] = 1;
		["Nick"] = 1;
		["Greg"] = 1;
	}
	
	print(names[math.random(1,40)])
end

return namesmodule

since this is a dictionary and not an array, you must supply a string as the KEY for the the value.

1 Like

How do you think i can go about that?

local Names = {"Bob", "Dan", "Landyn"}

local RandomiseName = Names[math.random(#Names)]

print(RandomiseName)
3 Likes

If you do @TheDCraft’s method then you won’t be able to print the value they store, but rather just the name. What you can do to make your current code work is this:

local randomNum = math.random(#names)
local chosenNameValue = nil
local counter = 1
for i, v in pairs(names) do
    if counter == randomNum then
        chosenNameValue = v
        break
    end
    counter++
end
1 Like

You could always do this: (I believe this would work)

local Names = {{"Bob", 1}, {"Dan", 1}, {"Landyn", 2}}

local RandomiseTable = Names[math.random(#Names)]
local Name, Value = RandomiseTable[1], RandomiseTable[2]
print(Name, Value)
1 Like

This is not a normal table, and more of a dictionary. You can try something like this:

local onlyGrabNames = {};
for key, value in pairs(names) do
-- Actual name would be key
table.insert(onlyGrabNames, key);
end
local chosen = onlyGrabNames[math.random(1,#onlyGrabNames)]
print(chosen)

Now say, you want 1 or 2, to change the chances, you can do:

local onlyGrabNames = {};
for key, value in pairs(names) do
-- Actual name would be key
for index = 1, names[key] do
table.insert(onlyGrabNames, key);
end
end
local chosen = onlyGrabNames[math.random(1,#onlyGrabNames)]
print(chosen)
1 Like