Switch-case in lua?

Adding switch-case for lua

Is your feature request related to a problem? Please describe (REQUIRED):
This idea comes from a worry that the significant use of elseif statements will affect the stability and performance of my game, while I know how to implement switch-case in vb, the lack of it here is infuriating

Describe the solution you’d like (REQUIRED):
What I am asking for is the implementation of switch-case as feature into the lua scripter, while their are other alternatives, (like building a table) or the switch function, most of what I have seen is quite incomprehensible for a relatively amateur coder such as myself

Describe alternatives you’ve considered (REQUIRED):
if not exactly switch case, a way to optimize coding else if statement that bypasses going through every individual elseif in some capacity would help immensely

We’re supporting Lua 5.1 and Luajit 2.1, and those doesn’t have support for switch statements.
As such, it isn’t something we’ll endeavour in trying to add to Lua, as our scripts would stop working when used with vanilla Lua/Luajit.

Have you actually made any measurements of this? It sounds like you plan to have thousands of if-elseif cases in your code. If that isn’t the case then why worry?

If you really are going to have a lot of checks then you could create a look-up table of values. Explained here: lua-users wiki: Switch Statement

6 Likes

@britzl is spot on here. If you are doing a large number of case selects in a switch type system, then you dont want to be doing that anyway :slight_smile:

Hash lookups are fast and you can make it very nice and easy to read/lookup. If you want to go a little further then you can use meta methods on the tested variable - this way, it “knows” what to call when you get a specific value.

You could make a switch statement too. Which is a little more effort, but based on something like this:

(See answer by codenio) You could genericise this method and end up with a fairly nice replica of switch.

3 Likes

Would agree look up tables are faster.

2 Likes