Value increment without wrapping – ShiVa Engine

Value increment without wrapping

Sometimes you need to increment/decrement a value and check the bounds, or even make the value wrap around. This logic is trivial to write, but do it too many times and it can occupy a lot of space. That’s why I encapsulated the functionality in this snippet. -by error454

--------------------------------------------------------------------------------
--  Function......... : cycleValue
--  Author........... : Zachary Burke
--  Description...... : Increases or decreases a variable, handles wrapping the
--                      value as well.
--
-- Examples:
-- Say you have a variable nCounter where the max value is 5 and the minimum is 0
--
-- Increment
--   nCounter = 4
--   nCounter = this.cycleValue ( nCounter, 0, 5, true, false )
--     Before: 4
--      After: 5
-- Increment but don't wrap
--   nCounter = 5
--   nCounter = this.cycleValue ( nCounter, 0, 5, true, false )
--     Before: 5
--      After: 5
-- Decrement and don't wrap
--   nCounter = 4
--   nCounter = this.cycleValue ( nCounter, 0, 5, false, false )
--     Before: 4
--      After: 3
-- Increment with wrapping
--   nCounter = 5
--   nCounter = this.cycleValue ( nCounter, 0, 5, true, true )
--     Before: 5
--      After: 0
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
function MainMenuAI.cycleValue ( nValue, nMin, nMax, bIncrement, bWrap )
--------------------------------------------------------------------------------
    local incrementAmount = bIncrement and 1 or -1
    nValue = nValue + incrementAmount
    if(bWrap)
    then
        if(nValue > nMax)
        then
            return nMin
        elseif(nValue < nMin)
        then
            return nMax
        end
    end
    if(bIncrement)
    then
        return math.min ( nValue, nMax )
    else
        return math.max ( nValue, nMin )
    end
--------------------------------------------------------------------------------
end
--------------------------------------------------------------------------------



Need more answers?

  • slackBanner