lua-users home
lua-l archive

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


Luiz Henrique de Figueiredo wrote:
> > I would prefer to write large table literals than to populate tables
> > by individual assignment, since I don't want to pay the costs for growth.
> 
> Oh well, I don't think there's a nice solution [...]

But there is. I'm not sure whether I've mentioned this, but LJ2
puts no limit (other than memory size) on the number of constant
keys/values of a table constructor.

The parser stores all constant key/value pairs into a lazily
allocated template table. It only emits store instructions for
variable keys or values. If a template table has been created,
it's put into the constant section. The table creation instruction
TNEW is then patched to the table duplication instruction TDUP.

$ lj2 -jbc -e 'local x = {}'

0001    TNEW     0   0

$ lj2 -jbc -e 'local v = 1; local x = {v}'

0001    KSHORT   0   1
0002    TNEW     1   3
0003    TSETB    0   1   1

$ lj2 -jbc -e 'local x = {1,2,3}'

0001    TDUP     0   0      ; {1,2,3}

$ lj2 -jbc -e 'local v = "var"; local x = {"x","y",v,foo=true,bar=v,[v]=v}'

0001    KSTR     0   0      ; "var"
0002    TDUP     1   1      ; {"x","y",foo=true}
0003    TSETB    0   1   3
0004    TSETS    0   1   2  ; "bar"
0005    TSETV    0   1   0

Note that neither "x", "y", nor "foo" appear in the bytecode or
the constants, because they are only part of the template table.

Ah, before I forget: duplicating a large table of constants is of
course a lot faster than filling it by executing tons of bytecodes.

--Mike