veternitzz / switch-luau

Switch.luau is a switch implementation in pure luau including the main switch function and also a case and default function.
https://veternitzz.github.io/switch-luau/
MIT License
2 stars 2 forks source link

This isn't a switch case... #7

Open LeFisheAuCoordLogger opened 2 months ago

LeFisheAuCoordLogger commented 2 months ago

What you have here is an autistic way of slowing down the program via an object oriented approach to a "switch case", which is really just a brute force/linear search as you keep adding cases until you find the matching value. This means that if we have a value that matches with the last "case", it will take longer for the program to reach it.

Switch cases are meant to be fast, they take an integer value, index a constant jump table (only initialized once in the program) and then jump to the corresponding instruction address. This indexing is done in a constant time complexity meaning every case takes the same time to be matched. In addition, if the switch case isn't broken, it falls through to the next case.

In a higher level (Java) this would be:

switch(5){
case 0:
case 1:
    System.out.println("Case 0 or 1");
    break;
default:
    System.out.println("Default case");
case 5:
    System.out.println("Case 5");
}

The most similar approach in Lua (efficiency wise) is initializing a constant table with functions as values and handle fall-throughs recursively:

function doTableSwitch(value,cases)
    local case = cases[value];
    local function FallThrough(case)
        return cases[case](FallThrough);
    end
    return (case or cases.default)(FallThrough);
end

cases = {
    [0] = function(FallThrough)
        return FallThrough(1);
    end,
    [1] = function(FallThrough)
        print("Case 0 or 1");
    end,
    default = function(FallThrough)
        print("Default case");
        return FallThrough(5);
    end,
    [5] = function(FallThrough)
        print("Case 5");
    end,
}

doTableSwitch(5,cases) 

I hope this clears up everything, consider renaming your "Switch Case" to "Redundant Object Oriented If Else".

ridglef commented 2 months ago

based and redpilled

veternitzz commented 2 months ago

100% Correct. I've deprecated this project in favor of a proper switch-case included in a project I'm working on. I did the implementation all wrong and somehow managed to make switch-case OOP.