I made a switch statement in lua

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
  }
);
1 Like

I personally don’t see the use of this. You could just do

if Condition == 1 then
    Statement1()
elseif Condition == 2 then
    Statement2()
else
    DefaultStatement()
end

or use tables

local Statements = {
    Statement1,
    Statement2,
    DefaultStatement
}

(Statements[Condition] or Statements[#Statements])()

did you even type

local Condition = 1

or

local Condition = 2

i don’t see it in your script how is the script supposed to know what condition is?

It’s example code, it’s not meant to be mindlessly copy-pasted. It’s not a full script, and it’s not meant to be.

2 Likes

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.

Actually, the example was using functions, not booleans, which is possible in Luau

eval not nil

eval not nil output

1 Like

Ah I get it now. They were functions, not booleans. Sorry for the mix-up,

1 Like

I now understand how this works as well, I didn’t even think of applying this anywhere. Thanks for showing me this.

Refer to this: Switch Statements In Lua

Your method is much more complicated than it needs to be.

You’re absolutely right about that, I can see where I could’ve simplified things. Granted, I made this off the top of my head.

Also, nice module.