lua-users home
lua-l archive

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


On Tue, Mar 19, 2013 at 5:00 PM, Ivo Beltchev <ivo@ibeltchev.com> wrote:
> I've recently struggled with this problem.
>
> I want to create inheritance of environments. I set the parent environment
> as __index for the child environment. So when you access a variable from the
> child environment that's not there, it will look at the parent. Pretty
> standard stuff - kind of like scopes and namespaces work in C++.
>
> Let's say the parent has {a=5, b=10}. The child has {a="five", c=true}. If I
> access "a" I will get "five" instead of 5. So far so good. The two a's are
> two very different variables. But if I set the child's a to nil, I will
> start using the one from the parent because there is no way to distinguish
> between "not defined" and "defined, but currently nil":
> print(a) -> five
> a=nil
> print(a) -> 5

This is exactly the use case for creating your own "null" value
distinct from nil. It's easy -- as I mentioned in another post, just
create a variable "null = {}" and it'll always compare equal to itself
but not equal to anything else.

If you want to soup it up some you can put some metatables on it to
error out if you try to index into it. Maybe have a null.lua
containing something like:

local null = {}
local nullmt = {}
nullmt.__index = function(self, key) error("attempt to index into null") end
nullmt.__newindex = nullmt.__index
setmetatable(null, nullmt)
return null

And then you can say:

local null = require("null")

This has the additional benefit of having null being the SAME null
across all of your source files.

/s/ Adam