How would I go about having functions in a table without the functions running before they're called via math.random()?

I have set attacks made and I input them in a table but for some reason they run right in the table?


Also I get an error when attempting to use math.random

1 Like

Seeing as you also provide arguments, you’d have to do it like this:

local attacks = {{shootFireballs, 25}, {spinRightAttack}, {spinLeftAttack}}

Then, you’d pick a random move by doing…

local function pickMove()
    local attack = attacks[math.random(#attacks)]
    attack[1](select(2, unpack(attack)))

If you’re wondering what the ominous select(2, unpack(attack)) does, I can explain.

The select function, among other things, is useful when dealing with varargs. select(n, …) will select the nth element in the vararg onwards. The unpack function turns a list table (NOT an associative or keyed table) into a vararg. So the line select(2, unpack(args)) will return all your arguments past the attack in vararg form.

As an example, this code…

local x = {1, 2, 3}
print(select(2, unpack(x)))

…will print 2 and 3.


Called functions do go toward table count. So when you are calling math.random(1,#attacks) it is seeing 0. Do print(#attacks) to see that.

What I would do is just put strings and use if statements.

local Attacks = {"ShootFireballs","SpinRight"}
local AttackChoice = math.random(1,#Attacks)
if Attacks[AttackChoice] == "ShootFireBalls" then

Edit use @Kampfkarren his is nicer


Thank you guys*

unpack can select arguments.

local x = {1, 2, 3}
print(unpack(x, 2))
--> 2 3

Didn’t know this. Very cool.

The only time called functions don’t add to the table is if they return nil. Otherwise the table will include whatever the function returns and will add to the table.

Functions in the table count just the same as anything else, too:

a = {function() end,function() end} print( #a)

prints 2

1 Like

I think that you should do it like that

local commands = {
	ban = {method = function()
	kick = {method = function()

and then call the function like that


It will not execute at start but only if you call it.
You don’t need to use If statements now.

1 Like

Hey! Thank you for the reply, but this thread is close to 2 years old! I’m a lot more knowledgeable in terms of programming than I was years ago, so this is quite simple stuff for me now.

1 Like

I didn’t think that You will read this xD, It will surely help others that see this thread in the future lol