Skip to content

Instantly share code, notes, and snippets.

@FreeBirdLjj
Last active December 27, 2023 00:22
Show Gist options
  • Save FreeBirdLjj/6303864 to your computer and use it in GitHub Desktop.
Save FreeBirdLjj/6303864 to your computer and use it in GitHub Desktop.
A way to write switch-case statements in lua.
print "Hello, switch"
-- Suppose we want to write the equivalent lua code of the following c code:
-- switch (a) {
-- case 1:
-- printf("Case 1.\n");
-- break;
-- case 2:
-- printf("Case 2.\n");
-- break;
-- case 3:
-- printf("Case 3.\n");
-- break;
-- default:
-- printf("Case default.\n");
-- }
local cases = {
[1] = function() -- for case 1
print "Case 1."
end,
[2] = function() -- for case 2
print "Case 2."
end,
[3] = function() -- for case 3
print "Case 3."
end
}
local a = 4
local f = cases[a]
if (f) then
f()
else -- for case default
print "Case default."
end
-- If the default case does not have to be handled, we can use the following auxiliary function:
local function switch(value)
-- Handing `cases` to the returned function allows the `switch()` function to be used with a syntax closer to c code (see the example below).
-- This is because lua allows the parentheses around a table type argument to be omitted if it is the only argument.
return function(cases)
local f = cases[value]
if (f) then
f()
end
end
end
local x = 2
switch (x) {
[1] = function() -- for case 1
print "Case 1."
end,
[2] = function() -- for case 2
print "Case 2."
end,
[3] = function() -- for case 3
print "Case 3."
end
}
@Core-commits
Copy link

Useful

@srijan-paul
Copy link

I use this small function:

_G.switch = function(param, case_table)
    local case = case_table[param]
    if case then return case() end
    local def = case_table['default']
    return def and def() or nil
end

usage:

switch(a, { 
        [1] = function()	-- for case 1
		print "Case 1."
	end,
	[2] = function()	-- for case 2
		print "Case 2."
	end,
	[3] = function()	-- for case 3
		print "Case 3."
	end
})

@LingleDev
Copy link

noice.

@MatteoKrsticDev
Copy link

really cool ad usefull

@Doge2Dev
Copy link

super usefull, thx

@mystery-z
Copy link

Didn't know this was a thing, helped a lot

@gitcrane
Copy link

This looks great. Can you add some comments to your code to help novices like me understand the lua chunk?

@AnoRebel
Copy link

Awesome, thanks

@Davemehari
Copy link

Thank you.

@Davemehari
Copy link

@switch.lua Thank you.

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