Page 1 of 2

How to send a random command

Posted: Wed Jan 20, 2010 9:23 pm
by Vadi
How to send a random command each time in an alias:
Code: [show] | [select all] lua
local commands = {"hi", "wave", "bye"}
local which = math.random(#commands)

send(commands[which])

Re: How to send a random command

Posted: Fri May 21, 2010 7:41 pm
by Fo-Rum
One of my biggest troubles with programming are new symbols. In the quote following quote:
local which = math.random(#commands)
What is the # doing? I've made a lot of lua scripts that have all sorts of functionality but I've never used or even seen # in lua.

Re: How to send a random command

Posted: Fri May 21, 2010 7:53 pm
by Vadi
http://www.lua.org/manual/5.1/manual.html#2.5.5

for indexed tables, it's how many elements are there (holes are accounted for), for strings, it's usually how many characters

so #commands in this example is 3

Re: How to send a random command

Posted: Fri May 21, 2010 8:03 pm
by Denarii
It's the length operator. It returns the number of entries in a table, the number of characters in a string or (I think) the number of digits in a number.

Re: How to send a random command

Posted: Fri May 21, 2010 8:25 pm
by Fo-Rum
Oh wow, that's useful. Thanks! I'll have to use it now so I can remember it!

Re: How to send a random command

Posted: Fri May 21, 2010 9:00 pm
by Vadi
Not really:

Code: Select all

> =#5
stdin:1: attempt to get length of a number value
stack traceback:
	stdin:1: in main chunk
	[C]: ?
> 

Re: How to send a random command

Posted: Fri May 21, 2010 11:27 pm
by Denarii
Yeah, I wasn't sure about numbers.

Re: How to send a random command

Posted: Thu May 27, 2010 7:55 pm
by Iocun
It will of course work fine if you do #tostring(5)

Re: How to send a random command

Posted: Fri May 28, 2010 6:50 pm
by WillFa
Vadi wrote:http://www.lua.org/manual/5.1/manual.html#2.5.5

for indexed tables, it's how many elements are there (holes are accounted for), for strings, it's usually how many characters

so #commands in this example is 3
No it doesn't count holes.
Code: [show] | [select all] lua
foo = {1,2,3,[5]=1}
print (#foo)  -->  3

Re: How to send a random command

Posted: Fri May 28, 2010 7:02 pm
by Vadi
yep