How to send a random command

User avatar
Vadi
Posts: 5035
Joined: Sat Mar 14, 2009 3:13 pm

How to send a random command

Post 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])

Fo-Rum
Posts: 32
Joined: Fri May 21, 2010 7:38 pm

Re: How to send a random command

Post 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.

User avatar
Vadi
Posts: 5035
Joined: Sat Mar 14, 2009 3:13 pm

Re: How to send a random command

Post 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

Denarii
Posts: 111
Joined: Thu Dec 03, 2009 10:54 pm

Re: How to send a random command

Post 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.

Fo-Rum
Posts: 32
Joined: Fri May 21, 2010 7:38 pm

Re: How to send a random command

Post by Fo-Rum »

Oh wow, that's useful. Thanks! I'll have to use it now so I can remember it!

User avatar
Vadi
Posts: 5035
Joined: Sat Mar 14, 2009 3:13 pm

Re: How to send a random command

Post 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]: ?
> 

Denarii
Posts: 111
Joined: Thu Dec 03, 2009 10:54 pm

Re: How to send a random command

Post by Denarii »

Yeah, I wasn't sure about numbers.

Iocun
Posts: 174
Joined: Wed Dec 02, 2009 1:45 am

Re: How to send a random command

Post by Iocun »

It will of course work fine if you do #tostring(5)

WillFa
Posts: 19
Joined: Mon May 10, 2010 4:16 pm

Re: How to send a random command

Post 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

User avatar
Vadi
Posts: 5035
Joined: Sat Mar 14, 2009 3:13 pm

Re: How to send a random command

Post by Vadi »

yep

Post Reply