lua-users home
lua-l archive

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


On 1/18/12, Jak Sprats <jaksprats@gmail.com> wrote:
> (...)
> My questions are
> 1.) "asql" and "shadow" are being used as dirt cheap "namespace"s to reduce
> the risk of people tampering w/ them inadvertently. Changing them on
> purpose is fine, but I want them namespace'd somehow, how does one do this
> in Lua, in a clean/performant way?
> 2.) is there a smarter trade-off than this nested approach?
>
> thanks,
>  jak
>

I'm not entirelly sure about what you want.

There are two "idiomatic" ways to do encapsulation in Lua:
 - "counter" is an object with (public) slots:
    counter = {
      inc = function(self) self.base + 1 ; return self.base end;
      base = 0;
    }

    print(counter:inc()) -- 1
    print(counter:inc()) -- 2
    counter.base = 42
    print(counter:inc()) -- 43
 - "counter" is an object whose public methods have access to upvalues
(for this purposes, akin to private variables)
    do
      local base = 0
      counter = {
        inc = function() base + 1 ; return base end;
      }
    end

    print(counter:inc()) -- 1
    print(counter:inc()) -- 2
    -- don't have access to the base value from here, only counter.inc does
    print(counter:inc()) -- 3

Both approaches have merits. The 1st is more open and straightforward
coming from the OOP world. The 2nd might be more familiar coming from
the FP world. Although you can create upvalues like I did with a "do
local a = 42 ... end" block it's more common to have a function that
creates locals and returns functions that reference those locals. Each
of the created functions will have it's own copy of the local (hence,
more memory).

To understand all this and more http://www.lua.org/pil/ is your friend
here. Roberto will prefer that you get this one
http://www.inf.puc-rio.br/~roberto/pil2/. I don't have the Blue Pil,
but I've read great things about it and judging by the first edition,
I believe it.

In fact, the proxy thing where you redirect table access to an hidden
table is a common pattern that is explained pretty well in the White
Pil. It motivated __pairs and __ipairs and __len for tables in Lua
5.2. Check this: http://snippets.luacode.org/snippets/Object_Proxy_106
it might be what you want or at least the basis to what you want.