Help with getting a value from module script

I have a module script that picks a random value but how do I get that value in a script


local function onCharacterAdded(character)
	task.wait(4)
	local RacePicker = require(script.ChoseRace)

  print(RacePicker.chosen)

end

Whenever I try running this code I get the error
image

2 Likes

Can you send the module script code?

If the code you sent is the module script code then ensure to return a value.

The first error seems to have appeared by means of returning nothing from the module script. You must have forgotten to return anything from the module script being used to retrieve a value. You need to do something like the following script in order to retrieve values:

-- Module script

local RacePicker = {
    ["chosen"] = workspace
}

return RacePicker
local Races = {
	Race_1 = "Me'tyr", 
	Race_2 = "Alfr",
	Race_3 = "Ztyr",
	Race_4 = "Husken",
	Race_5 = "Terral",
	Race_6 = "Astral"
}

--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(Races) 

local index = math.random(1, #array)
local chosen = array[index]
print(chosen)

the module script will print it but the script cant grab it

If the module script prints the value successfully, the only thing you should add at the end of your script is the line below:

return chosen

Module scripts’ functionality is to return something whenever they get required by another script. Hence return keyword should always be used.

Ok it fixes that issue but now it prints Nil instead of the value why is that? The print in the module script prints the actual value but the print in the server script prints nil

did I write this line wrong

print(RacePicker.chosen)

This is because the key “chosen” is not a valid key in the “RacePicker” table. You return the value as a string, not as a table. Therefore, you can just print the RacePicker variable as it holds the string.

print(RacePicker)

But if you want to pass the whole table in the module script with the “chosen” key set to random chosen string, you should be doing the following.

In the module script:

local chosen = array[index]
Races.chosen = chosen

return Races -- Return the table with the random chosen value inserted in Races

In the other script

print(RacePicker.chosen) -- Retrieve the value by indexing
1 Like