lua-users home
lua-l archive

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


Consider the following code:

local trim_pattern = "^%s*(.*%S)%s*$"

This pattern has been carefully debugged to do what I want
(remove leading and trailing blanks and return nil if there is
nothing else on the line). It looks very much like other patterns
also used in my application, lots of magic characters and not
much else, obscure unless carefully dissected. I give it a name
to make my program readable. I have no intention of ever
changing the value of trim_pattern.

When processed by `luac -l -l -p`, the result is

0+ params, 2 slots, 1 upvalue, 1 local, 1 constant, 0 functions
    1    [1]    LOADK        0 -1    ; "^%s*(.*%S)%s*$"
    2    [1]    RETURN       0 1
constants (1) for 0x2097840:
    1    "^%s*(.*%S)%s*$"
locals (1) for 0x2097840:
    0    trim_pattern    2    3
upvalues (1) for 0x2097840:
    0    _ENV    1    0

I.e. one local as well as one constant gets used up.

There is no need to use up a local: the value sits among the
constants anyway. The proposal is that

const trim_pattern = "^%s*(.*%S)%s*$"

should give:

0+ params, 1 slot, 1 upvalue, 0 locals, 1 constant, 0 functions
    1    [1]    RETURN       0 1
constants (1) for 0x2097840:
    1    "^%s*(.*%S)%s*$"   trim_pattern
upvalues (1) for 0x2097840:
    0    _ENV    1    0

Details:

1. New keyword const.
2. Syntax as for local, except that initialization is not optional.
3. Visibility from the line where it is declared to the end of the function.
4. Name must not equal that of any local variable in the function
or of an upvalue already referred to.
5. The use of a constant defined in a containing block implies the
creation of a new constant of the same name in this function.