How can I get one of these two random functions? I can’t remember how to do it. Each time I try to print out the number of items in the table, it says 0. I was wondering if somebody could help me out.
local tab = {
["TEST"] = function()
end,
["Test2"] = function()
end,
}
print(#tab)
local mad = tab[math.random(1,#tab)]
print(mad)
local Functions = {
TEST = function()
end,
Test2 = function()
end
}
function RandomValue(Table)
local AllValues = {}
for Index, Value in pairs(Table) do
table.insert(AllValues, {
Index = Index,
Value = Value
})
end
return AllValues[Random.new():NextInteger(1, #AllValues)]
end
local Function = RandomValue(Functions)
print(Function.Index, Function.Value)
with the RandomValue(Table) function you can get a random value with any table
it returns a table with the index and the value, you can see how I print them
local mt = {
__call = function(self)
local i = math.random(1, # self)
self[i]()
end
}
local functions = setmetatable({
function ()
print("First function")
end,
function ()
print("Second function")
end,
function()
print("Third function")
end,
}, mt)
while true do
functions()
wait(0.75)
end
Here is a method you could take, using meta-tables. Whenever you want a random function selecting just call functions() as if was a function.
local t = {
--This is test 1 function
[1] = function()
return "Test 1"
end;
--This is test 2 function
[2] = function()
return "Test 2"
end
}
print(#t)
--2
local tab = t[math.random(1, #t)]
print(tab())
--Test 2
This is what I would do if I need to do this, and you could just name the function by leaving a comment, or you can do this:
--Name of the functions
local name = {
"Test1";
"Test2"
}
--Table of the functions
local t = {
["Test1"] = function()
return "Test 1"
end;
["Test2"] = function()
return "Test 2"
end
}
print(#t, #name)
--0, 2
local tab = name[math.random(1, #name)]
print(t[tab]())
--Test 2