Cant fix this issue in which the error: ServerScriptService.Script.ModuleScript:35: attempt to index function with ‘Rarity’ would appear. Purpose is to get a certain rarity for an item which will be done in the module script and the script would use the rarity for relevant purposes.
Script:
local myModule = require(script:WaitForChild("ModuleScript"))
for i = 1, 500 do --just to test and see
local rarity = myModule.pick()
print(rarity)
end
Module script:
local spawndata = {
["Nothing"] = {
["Rarity"] = 1
},
["Silver"] = {
["Color"] = Color3.fromRGB(255, 255, 255),
["Multiplier"] = 2,
["Rarity"] = 0.3
},
["Gold"] = {
["Color"] = Color3.fromRGB(183, 203, 0),
["Multiplier"] = 3,
["Rarity"] = 0.15
},
["Ruby"] = {
["Color"] = Color3.fromRGB(255, 8, 0),
["Multiplier"] = 8,
["Rarity"] = 0.02
},
["Diamond"] = {
["Color"] = Color3.fromRGB(0, 255, 217),
["Multiplier"] = 25,
["Rarity"] = 0.001
}
}
function spawndata.pick()
local totalweight = 0
local selected = "Nothing"
for i,v in pairs(spawndata) do
totalweight += v.Rarity
end
local random = Random.new()
local rnd = random:NextNumber(0,totalweight)
for i,v in pairs(spawndata) do
if rnd < v.Rarity then
selected = i
break
end
rnd -= v.Rarity
end
return selected
end
return spawndata
To fix the issue mentioned, I removed spawndata. from pick(). Not sure why but now it says attempt to call a nil value.
function pick()
local totalweight = 0
for i,v in pairs(spawndata) do
totalweight += v.Rarity
end
local random = Random.new()
local rnd = random:NextNumber(0,totalweight)
local selected = "Nothing"
for i,v in pairs(spawndata) do
if rnd < v.Rarity then
selected = i
break
end
rnd -= v.Rarity
end
return selected
end
return spawndata
The intended items (ingredients) for this are not fixed, and randomly generated. The keys in this case are all rarities for the items.
Thank you so much. Fixed it completely. Could you recommend any resources to learn more about module scripts? The youtube tutorials are not much of a help.
The roblox documentation should be plenty enough for basic uses. ModuleScript
Just think module script as a special script to return a value (in your modulescript you are essentially returning spawndata table) when require() is called