Forum

> > CS2D > Scripts > Get random number from table?
Forums overviewCS2D overview Scripts overviewLog in to reply

English Get random number from table?

7 replies
To the start Previous 1 Next To the start

old Get random number from table?

GreenDevil
User Off Offline

Quote
How to get random number from table?
So like i just type
1
table1={1,3,2,4}

then it will get random numbers from the table
like

2 , 3 , 1 , 2 , 4 and so on...

Oh and i want to ask what the hell mean's this error!
>
1
bad argument to #1 to 'player' (number expected, got nil)

Please help i just learning lua and i don't get it I CANT LEARN IT

old Re: Get random number from table?

DannyDeth
User Off Offline

Quote
Well the error msg is a way to tell you that you did this ( or something else, I'm showing you what is causing the error ):
1
2
3
4
table1= { 1,2,3,4 }
if player(table1[1],"exists") then -- exists can be anything!
	msg("player 1 exists!")
end
The part that is wrong is the fact that you are using table1[1] and not a played ID, remember that a table is a way of storing multiple variables in one name, so table1[1] is equal to nil and not equal to a number.

Sorry is this sounds strange but it is what is wrong.

Now, accessing random table element:
1
table1[math.random(1,4)]
If you do not know the length of the table you need to use this:
1
table1[math.random(1, #table1)]
The way I put '#' before the table's name is a way to indicate to Lua that I want the total length of the table.

I hope I helped

old Re: Get random number from table?

GreenDevil
User Off Offline

Quote
Thank you so much!
But i getting another error
I just don't know why: (
1
2
3
4
5
6
7
8
9
10
11
if table==nil then table={} end
table.rtd={}

table.rtd.table1={1,2,3,4}

addhook("say","playersays")
function playersays(id,txt)
		if (txt=="!rtd") or (txt=="!rollthedice") then
			table.rtd.table1[math.random(1, #table.rtd.table1)]
			end
end

So i decide to post the code!

old Re: Get random number from table?

Banaan
User Off Offline

Quote
What's the use of the table.rtd table?

You shouldn't use table as a table, as this is already a table of the Lua standard library.

Rather use something like tbl as a table.

1
2
3
4
5
6
7
8
9
10
if rtd==nil then rtd={} end

rtd={1,2,3,4}

addhook("say","playersays")
function playersays(id,txt)
          if (txt=="!rtd") or (txt=="!rollthedice") then
               rtd[math.random(1, #rtd)]
          end
end

old Re: Get random number from table?

GreenDevil
User Off Offline

Quote
Can i ask the last question what means:

wrong number of arguments?

bad argument #2 to random(interval empty) ?

Aww man i never will learn lua properly!
edited 1×, last 06.02.11 03:12:40 pm
To the start Previous 1 Next To the start
Log in to reply Scripts overviewCS2D overviewForums overview