What is the most efficient way to write this If statement?

Hello
I have a code similar to this:

local weapon_model = getWeaponModel()
if a>3 and b<7 and weapon_model and weapon_model.val == 14 then 
     dosomething()
else 
   .................
   .................
end

In many cases however getWeaponModel() is called unnecessarily.
is there a way to put getWeaponModel() as part of the if statement without calling it twice?

Thanks

There isn’t much information here, but have you tried adding a debounce? You could also check for a specific property or change to see if getWeaponModel() was called correctly.

And maybe find a way so that getWeaponModel() doesn’t get called unnecessarily in the first place ?

You could move a>3 and b<7 to an outer if statement:

local failed = false
if a>3 and b<7 then
    local weapon_model = getWeaponModel()
    if weapon_model and weapon_model.val == 14 then 
        dosomething()
    else 
        failed = true
    end
else
    failed = true
end
if failed then
    -- ...
end
1 Like

You’re only calling it once, which is to set your variable to the result. The if statement is only checking for existence before comparing a sub item. If you know for a fact that your getWeaponModel() will return a valid answer and not nil then you could remove the first one. Otherwise you still have to check it’s existence.

It is possible that getWeaponModel can return nil. I am not sure that it will return valid model so I need to verify it.
What do you think about a code like this?

if a > 3 and b < 7 and (function() local model = getWeaponModel(); return model and model.val == 14 end)() then 
    doSomething() 
else 
    doSomethingElse() 
end

This is the most efficient way I have found.


if a>3 and b<7 then
    local weapon_model = getWeaponModel()

    if weapon_model and weapon_model.val == 14 then
        dosomething()
    end
else 
    .................
    .................
end