lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


>> 
> Then don't do constants:
> 
> t = {}
> t[_G] = function() <some stuff> end
> if t[_G] then t[_G]() else <default case> end
> 
> I would like to be able to do something like this:
> 
> mode = {}
> mode.x = {}
> mode.y = {}
> mode.z = {}
> obj = mode.x
> switch obj
>    case mode.x
>        <some stuff>
>        break
>    else
>        <default case>
> end
> 
> basically what it should do behind the scenes is make a table where you have all the cases and stuff where it would look like this: (even if it has to do it at runtime which would be kinda slow but once you have a large amount of cases it should be faster than if-then-else(if) chains)
> t={} t[mode.x] = somelabel t[mode.y] = someotherlabel <etc>
> 

When faced with a switch statement, any compiler is going to either decompose it into a series of “test and jump” sequences or it is going to create a jump table and index it based upon the switch expression (or, typically, a combination of the two). The test and jump is more generic, and of course is equivalent to the chained “if .. then .. else” construct. The jump table is more restricted but very much faster (constant time in fact regardless of the number of cases).

And you can of course do both of these in Lua too. For the first case, you just code normal if/then/else statements. For the second case, you place each “case” in its own function, and then put these functions into a table indexed by the “switch” expression. Voila! Constant time switch, with no new syntax needed.

—Tim