lua-users home
lua-l archive

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




On Fri, Aug 13, 2010 at 1:24 AM, steve donovan <steve.j.donovan@gmail.com> wrote:
On Fri, Aug 13, 2010 at 8:08 AM, Shawn Fox <shawnkfox@gmail.com> wrote:
> cleaner syntax instead of having to assign to a magic variable.  loadin is a
> great solution for this when your code exists in a separate file, but there
> ought to be a way to do this using a control block as well, perhaps a "doin"
> statement:

Well, we were briefly shown in env do .. end.  It could still be
revived as appropriate sugar over _ENV manipulation.

steve d.

I've not been reading the list long enough to see the "in env do" syntax, from going back and reading older posts I don't see any clear statements about why it was removed.  I did see a complaint about nested in env do statements though that indicated it didn't behave like I would have expected either.  I think the main issue is that I'd want actual scoping which would mean that the enviornment should always have a metatable which has the __index set to the current environment, so something like this:

foo={}
setmetatable(foo, {__index=_ENV})
in foo do
   <code>
   bar={}
    setmetatable(bar, {__index=_ENV})
    in bar do
        <code>
    end
end

However all of this should be possible without all of the work and magic variable assignments. It should just be implied which is what the "namespace" concept would do by handling all of this activity in a single keyword, so you could do this:

foo = namespace
    <code>
    bar = namespace
        <code>
    end
end

So this could would be equivalent to the prior script without having to create a table, setmetatable, and then use it in a "in env do / end" block.  I don't really care what the keyword is, but but most of the features are already in 5.2 work4 to do this other than parsing the syntax and rewriting it using _ENV

So the concept is that variable assignment would always store the value in the local environment, but variable lookup would first check the current environment and then chain through all the environments until it got to _G or any other _ENV that had no metatable. 

So you'd never be able to assign a value in a higher environment without creating a setX function in that environment, like this:

foo = namespace
    function setX(value) x = value end
    bar = namespace
        setX(999)
        x=x-111
        -- this would display 888
        print(x)
    end
    -- this would display 999, not 888
    print(x)
end