# Calling a function through indexing a table

Hey. I’m stumped on this topic, even though I’m thinking it should be simple. What I need to accomplish is to call a function (which is in a table) through indexing. If someone could help me with this, that’d be much appreciated!

How the function looks in the table:

``````local Table = {
foo = function(x)

end;
}
``````

How I’m currently trying to call it:

``````Table[math.random(#Table)](x) -- Randomised index
Table(x) -- Predetermined index
``````
1 Like

Yeah, I’m trying to call it like that, just through indexing the function.

1 Like

you cannot get a random number between nothing and #Table, there have to be two (integer) bounds while using math.random; try
– but math.random(#t) works in cases where t = not 0 because while doing math.random(#t) , 1 is automatically passed as the first bound

``````  local Table = {
foo = function(x)
return print(x)
end;
}

local m = math.random(1, #Table)
Table[m]("abc")
``````

I’m pretty sure you can, as I’ve done it before previously when indexing a table with math.random with normal variables. I’ll try doing it your way and see if it changes anything.

#Table might return 0 if you have `table_var = {}` and that would be an index out of bounds error…

``````local succ, err = pcall(Table[math.random(1,#Table)], var1, var2, ...)
if not succ then warn(err); end;
``````

Edited after @XxELECTROFUSIONxX said that it wouldn’t handle errors.

I was just saying an easy way to fire the function when indexing the table. Wasn’t saying, “do this code with no modifications what so ever”

I should also mention my error, sorry about forgetting to mention it:

``````bad argument #1 (interval is empty)
``````

That hopefully should make it easier to pinpoint for you all. Though I’m not sure why it would consider the length of the table empty.

You can’t do the `math.random(1, #t)` idiom for getting a random key-value pair from a dictionary.

I am pretty sure using `next` would work since a table’s dictionary part has no inherent order

``````local _, f = next(Table)
f()
``````
3 Likes

Gonna test this theory real fast for you.

Edit: Tested, only prints the first one in a table with 3 values.
If I’m not mistaken pairs and/or ipairs uses next to iterate through it to get the values.

Is the error coming from the #Table or from the math.random(#Table) ?

That works, thank you, now I just need to apply that to randomising.

It was coming from math.random(#Table).

Yeah that seems to be the case.

What can instead be done is having an array of functions only.

``````local Table = {
function() print("bar") end,
function() print("foo") end
}

Table[math.random(#Table)]()
``````
3 Likes

Oh wow. I didn’t think it would’ve been that simple. Thank you, kind stranger!