Each time i click a testButton, testEnergy lowers by 2 and each time that happens i get an error “attempt to call a nil value”, thats because there are only 3 functions, on 20 energy, 10 and 0, theres no in between. Is there way to mute that error?
local testButton = GUIcameras.Test
local testEnergy = 30
local testLabel = GUIcameras.TestLabel
testButton.Text = testEnergy
local minus = 2
local testFunctions = {
[20] = function()
testLabel.Visible = not testLabel.Visible
testLabel.Text = "Your energy is decent."
task.wait(0.8)
testLabel.Visible = not testLabel.Visible
end,
[10] = function()
testLabel.Visible = not testLabel.Visible
testLabel.Text = "You are getting low on energy."
task.wait(0.8)
testLabel.Visible = not testLabel.Visible
end,
[0] = function()
testLabel.Visible = not testLabel.Visible
testLabel.Text = "No energy!"
minus = 0
task.wait(0.8)
testLabel.Visible = not testLabel.Visible
end,
}
testButton.MouseButton1Click:Connect(function()
testEnergy -= minus
testButton.Text = testEnergy
testFunctions[testEnergy]()
end)
You can check it like this
rawget function checks if a thing exists in a table (first arg) with the given index (second arg) ,if it exists then it returns the value and if it doesn’t, it returns nil
if rawget(testFunctions,testEnergy) then
rawget(testFunctions,testEnergy)()
end
Rawget and Rawset just bypass metamethods
Yours and his both do table lookup, except his is completely useless since the OP does not use __index metamethod
fastest is to cache it
local func = testFunctions[testEnergy]
if func then func() end
You are getting that error because you’re attempting to call nil, if you’re trying to accomplish calling the nearest available function that is less than or equal to energy, you can find that by doing something like:
local energyFuncs = {
[0] = function()
return ">= 0 energy"
end,
[10] = function()
return ">= 10 energy"
end,
[20] = function()
return ">= 20 energy"
end,
[30] = function()
return ">= 30 energy"
end,
}
local function getHighestEnergyFunc(energy: number)
local highestReq, highestFunc
for req, func in energyFuncs do
if energy >= req and (not highestReq or req > highestReq) then
highestReq, highestFunc = req, func
end
end
return highestFunc
end
print(getHighestEnergyFunc(20)()) -- ">= 20 energy"
Otherwise, if you just need to call an energy function at that exact energy level, check if the function exists first before attempting to call it, by doing:
local energyFunc = energyFuncs[energy]
if energyFunc then
energyFunc()
end