lua-users home
lua-l archive

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


Andrea:

On Wed, May 13, 2020 at 4:22 PM Andrea <andrea.l.vitali@gmail.com> wrote:
> Now forgive me for asking this, even if I am a programmer I am not a Computer Science Engineer. My question is: why are new scopes created by "if", "for" and other statements and not only by function definitions and do...end statements? If one wanted a new scope one could easily type "do" (as in other languages we just open a curly brace). So why this is done implicitly? What is the advantage or the theoretical reason? Again forgive me for this maybe silly question - remember my background is not in computer science.

I think Lua creates new scopes every time you have a place where you
can have multiple statements, an hence you can type local
declarations. Near in mind lua if-then-else is not like C ( if stat1 {
else stat2 } ), where you have to use a compoound statement ( using
curly braces ). Lua defines functions, control structures, etc. in
term of blocks, which are sequentiually executed list of statements.
Once you use this, if you do not make the then /elseif / else part
open scopes you open a can of worms. Where it not scope, how do you
define the behaviour of local declarations in the then/else block. The
initialization may not get executed if the branch is not taken. But
the declaration? So to keep it simple and easily understandable is
preferrable to make the branches define scopes.

Lua designers may provide further explanations, but when using blocks
in if statements, it is simpler to make them become scopes than to try
to define every code path in a sensible and understandable way.

You do not have this problem in C because variable declarations are
not statements which can appear after an if ( I mean "if(1) int i=1;"
is not legal ), so if you wanto to declare, you are forced to open a
new scope.

And you can find the same problem with variables declared in a never
executed loop body, it is simpler if the while uses a scope. (
remember, in lua while x() do y() end cannot be shortened, as in C, to
while x() y(), do and end are mandatory and they delimit a block.

The lua approach is normally simpler. A little more verbose some
times, but simpler. AAMOF, I tend to always define scopes in C, the
extra effort to put the braces is dwarfed by the brain cycles saved by
not having to worry about how to parse the if when reading my 10 year
old code. I only use naked if in idiomatic ( for me ) ways ( among
other things, always single line and without else ).

Francisco Olarte.
_______________________________________________
lua-l mailing list -- lua-l@lists.lua.org
To unsubscribe send an email to lua-l-leave@lists.lua.org