lua-users home
lua-l archive

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


> I've been poking around at the VM and its compiler, trying to learn
> how constants are handled.  It appears that
> 
>  1. A typical infix operator can take B and C operands that might be
>     constant, so for each operand, distinguishing a constant from a
>     register requires a conditional test (e.g., whether a particular
>     bit is set).
> 
>  2. Every function has its own pool of constants.
> 
>  3. As long as the number of constants in a function is small, source
>     code like
> 
>       n = n + 1   -- assume `n` is local here
> 
>     will compile to a single VM instruction.
> 
>  4. If the number of constants in a function gets large, to the point
>     where there aren't enough bits to pack them all into a B or C
>     operand, *from that point onward* no more constants are packed
>     into a B or C operand.  In other words, if the assignment `n = n + 1`
>     is compiled *after* the compiler has seen a large number of
>     constants, then it compiles to two VM instructions: one to load
>     the literal 1 into a register, and one to do the addition.
> 
> Does this summary seem accurate?  It's the last point that I'm really
> curious about?

Yes, up to version 5.3. (Version 5.4 created several different opcodes,
mainly to avoid the tests you mentioned in item 1.)  In the last point,
it should be noted that Lua reuses constants, so if the assignment `n
= n + 1` is compiled after the compiler has seen a large number of
constants, but 1 was one of those previous constants, the compiler
reuses that 1 and therefore codes the operation in a single opcode.

-- Roberto