tags:

views:

149

answers:

2

Hi - I've been playing around with a .lua file which passes a random phrase using the following line:

SendChatMessage(GetRandomArgument("text1", "text2", "text3", "text4"), "RAID")

My problem is that I have a lot of phrases and the one line of code is very long indeed.

Is there a way to hold

text1
text2
text3
text3

in a list somewhere else in the code (or externally) and call a random value from the main code. Would make maintaining the list of text options easier

Many thanks

Joe

NB - apols if this is double posted - had a problem getting past the logon :(

+2  A: 

You want a table to contain your phrases like

phrases = { "tex1", "text2", "text3" }
table.insert(phrases ,"text4") -- alternative syntax
SendChatMessage(phrases[math.random(table.getn(phrases))], "RAID") -- getn get's the size of the table. math.random gets a random number (with a max of the size of the phrases table) and the phrases[] syntax returns the table element at the index inside [].
olle
+1  A: 

For lists up to a few hundred elements, then the following will work:

messages = {
    "text1",
    "text2",
    "text3",
    "text4",
    -- ...
}
SendChatMessage(GetRandomArgument(unpack(messages)), "RAID")

For longer lists, you would be well served to replace GetRandomArgument with GetRandomElement that would take a single table as its argument and return a random entry from the table.

Edit: Olle's answer shows one way that something like GetRandomElement might be implemented. But it used table.getn on every call which is deprecated in Lua 5.1, and its replacement (table.maxn) has a runtime cost proportional to the number of elements in the table.

The function table.maxn is only required if the table in use might have missing elements in its array part. However, in this case of a list of items to choose among, there is likely to be no reason to need to allow holes in the list. If you need to edit the list at run time, you can always use table.remove to remove an item since it will also close the gap.

With a guarantee of no gaps in the array of text, then you can implement GetRandomElement like this:

function GetRandomElement(a)
    return a[math.random(#a)]
end

So that you send the message like this:

SendChatMessage(GetRandomElement(messages), "RAID")
RBerteig
Awesome - just what I was after. Big thanks. Joe
Joe