[solved] How to print a random index and his value from a module script

so im trying to get the index from a module script and print the index and his value, but idk how,
i search and try some methods but all is just value not index and value

(here the table from the module script btw):

local module = {
	["hello"] = 1;
	["itwasme"] = 2;
	["Menacing laugh"] = 3;
	["Yare yare daze"] = 4;
	["gang dance"] = 5;
}

return module

(and here is some of the methods that i try to use but only gets the index)

game.ReplicatedStorage.RollEmote.OnServerEvent:Connect(function(player)
	local module = require(game.ServerScriptService.QuotesSlotsDS.EmoteList)

	local function toArray(dictionary)
		local result = {}
		for index, v in pairs(dictionary) do 
			table.insert(result, index)
		end
		return result 
	end

	local array = toArray(module) 

	local index = math.random(1, #array)
	local chosen = array[index]
	print(chosen)
	
end)
1 Like
local module = {
	[1] = "hello",
	[2] = "itwasme",
	[3] = "Menacing laugh",
	[4] = "Yare yare daze",
	[5] = "gang dance",
}

return module

-------------- in another script

local randomIndex = math.random(1,#module)
local hisValue = module[randomIndex]


1 Like

i try it but gives this error, but i think that is just getting the index on the table, what i want to know is how to get an index on a table with HIS value

1 Like

you can use table.find(table, theValue)

1 Like

because your keys are strings and not integers you have to convert your keys into a numerical structure as follows:

local module = {
	["hello"] = 1,
	["itwasme"] = 2,
	["Menacing laugh"] = 3,
	["Yare yare daze"] = 4,
	["gang dance"] = 5
}



local keys = {}
for key, _ in pairs(module) do
	table.insert(keys, key)
end

local randomIndex = math.random(1, #keys)
local randomKey = keys[randomIndex]
print(module[randomKey])

I’ve written this all in the same script but you can still use the module format that you are utilizing with the proper edits.

2 Likes

well the print what i wanted was this

print(module[randomKey], randomKey)

but it does work, thanks buddy ^-^

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