Select a random phrase from the list

I played with a .lua file that passes a random phrase using the following line:

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

My problem is that I have many phrases and one line of code is very long.

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. It would help simplify the list of text options.

+3
source share
2 answers

For lists of up to several hundred items, the following will work:

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

GetRandomArgument GetRandomElement, .

: Olle , - GetRandomElement. table.getn , Lua 5.1, (table.maxn) , .

table.maxn , . , , , , . , table.remove , .

, GetRandomElement :

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

:

SendChatMessage(GetRandomElement(messages), "RAID")
+3

,

phrases = { "tex1", "text2", "text3" }
table.insert(phrases ,"text4") -- alternative syntax
SendChatMessage(phrases[math.random(table.getn(phrases))], "RAID") 

: getn ; math.random ( ), phrases[] [].

+2

Source: https://habr.com/ru/post/1717199/


All Articles