As the title says, I implemented the JavaScript switch statements into Lua. What do you think of the application?
Features:
Use of multiple conditions
Source code:
-- play around with num1 and num2
-- make one of them more or less than the other, or make your own datatypes
local num1 = 0;
local num2 = 100;
-- change this if you see improvements that can be made
local function switch(...)
local cases = {...};
local defaultCase;
local pos = false;
for i = 1,#cases,1 do
if (cases[i].case == true) then
cases[i].func();
pos = true;
break;
elseif (cases[i].case == "default") then
defaultCase = cases[i];
end
end
if (pos == false) then
defaultCase.func();
end
end
--[[
all cases (conditions) are in the form of a dictionary
for examples:
case1 = {
case = boolean OR "default"
func = function() *function code goes here* end
}
]]
switch(
{
case = num1 > num2,
func = function()
print("num1 is more than num2");
end
},
{
case = num1 < num2,
func = function()
print("num2 is more than num1");
end
},
{
case = "default",
func = function()
print("This is the default function");
end
}
);
Your first method works, but its inefficient when it comes to big comparison chains. That’s where the switch statement comes in.
Your second method however, wouldn’t work. Assuming Statement1 and Statement2 are both Booleans, Lua will pick up on that and will treat it as a Boolean, and not a normal piece of text, thus throwing an error because you cannot create functions via Booleans.