• There is NO official Otland's Discord server and NO official Otland's server list. The Otland's Staff does not manage any Discord server or server list. Moderators or administrator of any Discord server or server lists have NO connection to the Otland's Staff. Do not get scammed!

A question about math.random

Darth_Salva

New Member
Joined
Oct 15, 2007
Messages
30
Reaction score
0
Well... I'm learning scripting, and some time ago i saw a script where it was used the math.random to select an ID from an array...

That's the question: How to use the math.random to select ONLY ONE of the different IDs inside of an array? Example:

local array = {1234, 4321, 5544, 9966}
And use the math.random() to select one of them.

For now i'm using the only way i know:
Code:
local item = 0
local select = math.random(1, 4)
if select == 1 then
   item = 1234
elseif select == 2 then
   item = 4321
and so on...

That works but is tedious and long if you want to do many possible results...
 
You mean, like this?
Code:
local table = { 1234, 4321, 6543, 3213 }
doPlayerSendTextMessage(cid, MESSAGE_INFO_DESCR, table[math.random(1, table.maxn(table))])
 
I don't know... The script chooses a value between 1 and the max number inside the array?

I'm searching for a way to do this: choose randomly only values inside the array "table = { 1234, 4321, 6543, 3213} "; So the result of mat.random could be ONLY one of these: 1234, 4321, 6543, 3213.

Thanks... testing, i'll edit when finish...
 
Code:
local results = {
	[1] = { 1234 },
	[2] = { 3421 },
	[3] = { 6521 },
	[4] = { 8882 }
}

function onUse(cid, item)
	local rand = math.random(1, 4)
	for key, value in pairs(results) do
		if rand == key then
			doPlayerSendTextMessage(cid, MESSAGE_INFO_DESCR, value)
		end
	end
	return TRUE
end

Well, both would only return the number from the table.
 
Yeah, that works too; Well, i was looking for a shorter way to do the same, like: math.random({1234}, {4321}, {5742}, {8954}) (this example don't works)...

I mean, a way to indicate to the random function to only do those chooses without arrays or variables.
 
Yes and that's how he did :)

But to make it even shorter you could make a function that you could use each time you need it :p
Code:
function table.random(t)
    return t[math.random(1, #t)]
end
 
Back
Top