Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
0

Indexing a table of functions?

Asked by
trecept 367 Moderation Voter
5 years ago

So with a normal table

normaltable = {"hello", 4, 100}

I can do

normaltable[math.random(1, #normaltable)]

and I will get a random value inside the table. However if I have functions like:

functiontable = {}
functiontable.Print = function()
    print("hi")
end)

functiontable.Print2 = function()
    print("hello")
end)

I cant use the random pick as I was for the first one as it can't get the length of the table. What would be an alternative to get a random function from a table of functions?

1 answer

Log in to vote
1
Answered by 5 years ago

The reason for this is because you created a dictionary.

When a dictionary is created, the keys inside of it do not have an order. Because of that, iterating through a dictionary may not give the values in the order you wrote. And a dictionary's values are stored in keys, unlike tables that are stored in indexes. In order to fix this, you should preset the functions and make it a normal table.

local function Print() 
    print("hi")
end

local function Print2()
    print("hello")
end

local functiontable = {Print, Print2} -- Remember to use local variables. 
functiontable[math.random(1, #functiontable)]()
-- Calls a random function

----OR----
local functiontable = {}-- Remember to use local variables. 

local function Print() 
    print("hi")
end

local function Print2()
    print("hello")
end

table.insert(functiontable, Print)
table.insert(functiontable, Print2)
tablefunction[math.random(1, #functiontable)]()
-- Calls a random function 
0
Thank you! trecept 367 — 5y
Ad

Answer this question