How do I call a function from a table?

Hello! For the past hour, I’ve been trying to call a function from a table, but I end up getting an error. Can anyone show me or link me some resources on how I can do this please?

Keep in mind im still pretty new to tables.

Code:

local WeatherManager = workspace.WeatherManager
local WeatherParticles = WeatherManager.WeatherParticles

local WeatherTypes = require(game.ReplicatedStorage.WeatherTypes)

local Weather = {
	[1] = WeatherTypes.Sunny(),
	[2] = WeatherTypes.Foggy(),
	[3] = WeatherTypes.PartlyCloudy(),
	[4] = WeatherTypes.Rainy(),
	[5] = WeatherTypes.Cloudy(),
	[6] = WeatherTypes.Nighttime()
}

while true do
local tab = Weather[math.random(1, #Weather)] -- this errors sadly
	-- how run a random function from the Weather table???
	wait(5)
end
2 Likes

You should try this:

local Weather = {
    WeatherTypes.Sunny,
    WeatherTypes.Foggy,
    WeatherTypes.PartlyCloudy,
    WeatherTypes.Rainy,
    WeatherTypes.Cloudy,
    WeatherTypes.Nighttime
}

while true do
    local tab = Weather[math.random(1, #Weather)]()
    task.wait(5)
end

The problem is that you’re calling the functions in the table and it stores the return value(s) in the table. Assuming it returns nil, then nothing will be in the table and all of your functions get called. What you can do instead is store references to the functions in the table and then call it when you pick a random one

Also note that for arrays, specifying the indices are not necessary

3 Likes