Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Selecting random phrase from a list

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.

like image 442
Joe Avatar asked Feb 15 '26 19:02

Joe


1 Answers

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")
like image 68
RBerteig Avatar answered Feb 20 '26 03:02

RBerteig



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!