[Date Prev][Date Next][Thread Prev][Thread Next]
[Date Index]
[Thread Index]
- Subject: Re: duplicated local variables with same name
- From: Patrick Donnelly <batrick@...>
- Date: Mon, 15 Jun 2015 12:25:31 -0400
On Mon, Jun 15, 2015 at 11:16 AM, Dirk Laurie <dirk.laurie@gmail.com> wrote:
> 2015-06-15 15:26 GMT+02:00 Jinhua Luo <luajit.io@gmail.com>:
>
>> Maybe the reference should describe more: "local" should be used
>> once to declare new local variable (with different variable name).
>> After all, the max number of local variables is limited due to the opcode
>> format.
>
> The manual says in §3.5:
>
> Notice that each execution of a local statement defines new local
> variables.
>
> That implies that the code
>
> local val = 1
> local val = 1
> local val = 1
>
> will three times create a local variable called "val" and initialize it
> to 1. This may be a silly, sloppy and stupid thing to do but it is not
> illegal, and as "Rena" has pointed out, it is possible to write code
> in which reusing the name is the intended behaviour.
The correct idiom (but not really) is to do this:
do
local x, y = ...
end
do
local x, y = ...
end
That reuses the registers for x and y so you could repeat those blocks
forever without problems.
[It's a shame that declaring blocks that limit temporary variable
scope isn't more popular, perhaps the extra two lines and bonus
character in 'end' bothers OCD people like myself. I'm a fan of using
{} in C code but I admit it always looks weird.]
--
Patrick Donnelly