✓ Accepted answer
Hello there! This is not too difficult/complex to do. The simplest method I could think of, was 1.) get the length of the dictionary, 2.) randomly choose a number in that length, 3.) loop until you reach that random number. Because the iterator, pairs, is arbitrary already, this should leave you with a pretty random selection. You cannot just get the length of a dictionary with the # operator in Lua. You would have to create your own method. I recently posted three different methods discussed here. Ok, so now to the example:
local function dictLengthFinder(tbl)
local length = 0
for i,v in pairs(tbl) do
length = length + 1
end
return length
end
local function getRan(dict)
local dictLength = dictLengthFinder(dict)
local ranIndex = math.random(dictLength)
local counter = 1
for i,v in pairs(dict) do
if counter ~= ranIndex then
counter = counter + 1
else
return v
end
end
end
local dict = {}
local ranItem = getRan(dict)
I hope this helps. Have a great day scripting!
Edit:
For the value to determine the probability would be rather inefficient, and there are probably better ways you could structure your code in order to remove the need for this. I will, however, walk you through how to accomplish this. 1.) create a table named chanceTbl (for this example) 2.) loop through your dictionary and store the index value amount of times in the chanceTbl 3.) randomly select an index in the chanceTbl and return the value, which would be the index in your dictionary. Here is an example:
local function getRan(dict)
local chanceTbl = {}
for i,v in pairs(dict) do
for num = 1, v do
table.insert(chanceTbl, i)
end
end
local ranIndex = math.random(#chanceTbl)
local ranItem = chanceTbl[ranIndex]
return ranItem
end
local dict = {}
local ranItem = getRan(dict)
Good luck!
2 comments
If you want the value to be the chance of it being returned, that is just to complex and inefficient. I recommend that you change your code structure so you don't need to do that.
No problem. Glad I could help!