Skip to content

Instantly share code, notes, and snippets.

@mattkrins
Last active March 21, 2017 10:59
Show Gist options
  • Save mattkrins/0d39939f6a881867f5d74df7f72d8a17 to your computer and use it in GitHub Desktop.
Save mattkrins/0d39939f6a881867f5d74df7f72d8a17 to your computer and use it in GitHub Desktop.
A Garry's Mod Switch Statement helper function.
local s function switch(v) s = v or false return s end
function case(v, yes, no) if s and v and (v==s) then if yes then return yes(s, v) end return true end if no then return no(s, v) end return false end
function clearSwitch() s=nil return true end
@mattkrins
Copy link
Author

mattkrins commented Mar 2, 2017

Usage:

switch( value any ) // Load the switch with a value (required)
case( checkValue any, onTrue function[switchValue any, caseValue any],  onFalse function[switchValue any, caseValue any] ) // Check the switch and return true/false or execute a 1st and 2nd function argument if supplied.

Example:

local input = 2

switch( input )

case( 1, function( c )
  print( "Case was " .. c )
end, function( c, s )
  print( "Case was not " .. s )
end )

case( 2, function( c )
  print( "Case was " .. c )
end )

switch( 4 )

local result = case( 3 )
if result then print( "Case was " .. result ) end

if case( 4 ) then print( "Case was 4" ) end

local function testFunc(c, s)
  print( "Case was " .. s )
end
case( 5, testFunc )

clearSwitch() // not required, clears stored switch data for security reasons.

Result:

Case was not 1
Case was 2
Case was 4

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment