lua-users home
lua-l archive

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


It was thus said that the Great Paige DePol once stated:
> 
> > But this:
> > 
> > 	switch(x)
> > 	  case 1
> > 	    print("foo")
> > 	  case 2
> > 	    print("bar")
> > 	  else
> > 	    print("wtf")
> > 	end
> > 
> > is more like:
> > 
> > 	if x == 1 then
> > 	  print("foo")
> > 	end
> > 	if x == 1 or x == 2 then
> > 	  print("bar")
> > 	end
> > 	-- ... um ... is "wtf" always printed?
> 
> Yes, but obviously in this case the switch statement makes it far clearer
> as to what is going on.
> 
> Also, yes in your example above the else block would always be executed as
> you have no break statements at all, so everything will just fall through
> to the end of the switch. As should be expected and is also how it would
> work in C.

  Actually, C uses 'default', not 'else'.  That's what threw me for a loop.

> >  Okay, if each case has a "break" statement [1] then an optimization might
> > be to convert the switch statement to a table.  Go, going back to my first
> > example, it would internally be converted to: {snip}
> 
> Your examples involve the use of tables and functions, both of which are
> unnecessary overhead that I would not want to incur for every switch
> statement that is used. Actually, I am unsure how that would qualify as an
> optimisation really? 

  For space, it's not.  It's a time-optimization, as using a hash table is
O(1) (amortized) overhead.  Also, the table/functions are only created once,
during compilation.  For large switch statements with equal (or near equal)
probability of among cases, I would think it's a win over a cascade of
if/elseif statements.

  -spc