1)
To simplify the if else conditions, use <
instead of >=
.
Note: This only works correctly if number
isn't a decimal. Be sure to round.
Old Code:
if(number >= 100) then doSetInc(id, 8, 20)
elseif(number >= 91) then doSetInc(id, 8, 30)
elseif(number >= 81) then doSetInc(id, 8, 50)
elseif(number >= 7) then doSetInc(id, 8, 70)
elseif(number >= 1) then doSetInc(id, 8, 100)
end
New Code:
if( 99 < number ) then doSetInc(id, 8, 20)
elseif(90 < number ) then doSetInc(id, 8, 30)
elseif(80 < number ) then doSetInc(id, 8, 50)
elseif( 6 < number ) then doSetInc(id, 8, 70)
elseif( 0 < number ) then doSetInc(id, 8, 100)
end
2)
Create a function that retrieves the value of the third parameter, since that's the only thing that changes for the doSetInc
calls.
3)
Rename doSetInc
to setInc
.
4)
Declare variables as local
, unless global
is required.
Final Code
-- core function
local getGrade = function(x)
local val
if ( 99 < number ) then val = 20
elseif (90 < number ) then val = 30
elseif (80 < number ) then val = 50
elseif ( 6 < number ) then val = 70
elseif ( 0 < number ) then val = 100
return val;
end
setInc(id, 8, getGrade( number ) )
Use case:
local number = 10
local id = "283"
local setInc = function(a,b,c)
print( "setInc("..a..", " .. b .. ", " .. c .. ")" )
end
setInc(id, 8, getGrade( number ) )