lua-users home
lua-l archive

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


On Sunday 09 May 2004 05:26, Quinn Tyler Jackson wrote:
>  > By the way, is there some way of creating "real
>  >
> > > #defines" in Lua?
> >
> > You don't need to. Because Lua strings are pooled, the equality
> > test is just a
> > pointer comparison, so the following is a perfectly efficient way to do
> > things:
> >
> >     if enemy.type == "ENEMY1" then ... end
> >
> > Or if there are lots of choices:
> >
> >     local switch = { ENEMY1 = function() ... end, ENEMY2 = ... }
> >     switch[enemy.type]()
>
> The above use of tables with functions to emulate switches caught my eye,
> so I tried it with a long if ... elseif ... end chain (well, 8 choices ...
> not so long, and I used a global rather than local table for the choices),
> and it turned out to profile exactly the same speed as the if ... elseif ..
> end chain. (The local table version was about 1 ms. slower for my test.)

Mmm, you're right. Looks like you need a few hundred options before the table 
method actually becomes faster. The advantage it does have is that it's a 
value dispatch: you can group the all code for dealing with each constant 
together rather than than spreading it throughout the code. Makes it easier 
to add new constants.

-- Jamie Webb