How to send a random command

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

How to send a random command

Post by Vadi » Wed Jan 20, 2010 9:23 pm

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 » Fri May 21, 2010 7:41 pm

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: 4721
Joined: Sat Mar 14, 2009 3:13 pm

Re: How to send a random command

Post by Vadi » Fri May 21, 2010 7:53 pm

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 » Fri May 21, 2010 8:03 pm

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 » Fri May 21, 2010 8:25 pm

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

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

Re: How to send a random command

Post by Vadi » Fri May 21, 2010 9:00 pm

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 » Fri May 21, 2010 11:27 pm

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 » Thu May 27, 2010 7:55 pm

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 » Fri May 28, 2010 6:50 pm

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: 4721
Joined: Sat Mar 14, 2009 3:13 pm

Re: How to send a random command

Post by Vadi » Fri May 28, 2010 7:02 pm

yep

Post Reply

Who is online

Users browsing this forum: No registered users and 3 guests