lua-users home
lua-l archive

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


On Fri, Apr 26, 2013 at 8:53 AM, Coda Highland <chighland@gmail.com> wrote:
> On Fri, Apr 26, 2013 at 8:48 AM, Doug Currie <doug.currie@gmail.com> wrote:
>>
>> On Apr 26, 2013, at 7:13 AM, Thomas Jericke <tjericke@indel.ch> wrote:
>>
>>> To me there are still some problems regarding scoping with this, consider:
>>>
>>> if someboolean then
>>>    global myvar = 0
>>> end
>>>
>>> print(myvar) -- Is this valid?
>>>
>>> Probably the most consistent way would be, that scoping is used for globals too and you would have to do this:
>>>
>>> global myvar
>>>
>>> if someboolean then
>>>    myvar = 0
>>>    global g2
>>> end
>>>
>>> print(myvar) -- ok
>>> g2 = 0 -- error
>>
>> If this is what you want, then the local and global keywords mean the same thing. In expression oriented languages of the ML family, this keyword is called val. It declares a new value in the present scope. So your example becomes:
>>
>> val myvar
>>
>> if someboolean then
>>    myvar = 0
>>    val g2 = 7
>> end
>>
>> I like this approach, but I am not advocating a change to Lua.
>>
>> This can also be accomplished with a new operator. In mathematics, := is often used for definitions.
>>
>> myvar := nil -- global declaration and initialization
>>
>> if someboolean then
>>    myvar = 0 -- assignment
>>    g2 := 7   -- local declaration and initialization
>> end
>>
>> I am not advocating this either, but it may spark some derivative language experiments.
>>
>> e
>>
>>
>
> No, they don't quite mean the same thing. They mean the same thing in
> terms of the scope of the *name*, but not the scope of the *value*.
> Multiple "local x" statements each create a new local variable named
> x, while multiple "global x" statements would all refer to the same
> global variable named x.
>
> Consider:
>
> global x = 3
>
> function foo(y)
>     print(x) -- error
>     if y > 5 then
>         global x = 6
>         print(x) -- legal
>     end
>     print(x) -- error
> end
>
> print(x) -- legal, outputs 3
> foo(8) -- legal assuming you take out the print statements
> print(x) -- legal, outputs 8
>
> /s/ Adam

Actually, I realized a flaw in my example, here's a revision:

foo.lua:

global x = 3

function foo(y)
    print(x) -- error
    if y > 5 then
        global x = 6
        print(x) -- legal
    end
    print(x) -- error
end

bar.lua:

local foo = require "foo"

print(x) -- error

global x
print(x) -- legal, outputs 3
foo.foo(8) -- legal assuming you take out the print statements
print(x) -- legal, outputs 8

/s/ Adam