lua-users home
lua-l archive

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


On Monday 28 February 2005 16.05, crow wrote:
> David Olofson <david@olofson.net> wrote:
> (27/02/2005 22:03)
> 
> >The tricky part is avoiding a dummy initialization before code like 
> >this:
> >        //y = 0;   // No, thanks!
> >        if a
> >                y = 1;
> >        else
> >                y = 2;
> >
> 
> David, did you mean 'No thanks' as in: not wanting the ugly extra
> assignment to zero? 

Yep, seing that the compiler "should" be able to figure out that 
there's no way 'y' can be uninitialized after that if statement. 
However, though it may be easy for us to spot, it's not that trivial 
for a compiler... (Well, the theory is simple, but I think even a 
special case for this particular type of situation would amount to a 
few lines of code.)

The obvious easy way out would be to just catch any initializations in 
a conditional context, and throw in an implicit initialization before 
the "offending" statement, but it's tricky to insert code after the 
fact like that, and maybe even more so with a compiler that issues VM 
code directly.


> In a case like this, I use this:
> 
>  y = 2
>  if a then  y = 1  end
>
> Only two, no 'else' and no chance of a var depending on a
> conditional branch merely for its prior existence... 

Right, that's the universal solution; works with pretty much every 
language. The only problem is that it's kind of wasteful if the 
assignment is more expensive than loading a value into a register or 
similar.

If you're creating + filling in a table, you'd just initialize with an 
empty table, but I don't know if that's as efficient as doing 
creation + initialization in one step. Depends on whether or not the 
VM has any significant shortcuts for that case - but unless I'm 
missing something, the Lua VM just has a NEWTABLE instruction that 
you have to use either way.


//David Olofson - Programmer, Composer, Open Source Advocate

.- Audiality -----------------------------------------------.
|  Free/Open Source audio engine for games and multimedia.  |
| MIDI, modular synthesis, real time effects, scripting,... |
`-----------------------------------> http://audiality.org -'
   --- http://olofson.net --- http://www.reologica.se ---