[Date Prev][Date Next][Thread Prev][Thread Next]
[Date Index]
[Thread Index]
- Subject: Re: scope, design patterns?
- From: Javier Guerra Giraldez <javier@...>
- Date: Mon, 27 Dec 2010 21:30:12 -0500
On Mon, Dec 27, 2010 at 8:01 PM, Patrick Mc(avery
<spell_gooder_now@spellingbeewinnars.org> wrote:
> Is there a way to have nested tables that do not have access to each other?
tables don't 'access' each other, since they're data, not code.
i guess what you mean is that each subtable contains some code that
was defined separately, and where local variables of one aren't
accessible by the other.
not hard to do. in a single Lua file:
-----------------------------------------------
local maintable = {}
do -- subproject A
local A = {}
maintable.A = A
local privatevar = ........... -- local variables
local function privatefunc () -- local function
.......
end
A.someNum = 45 -- public variable
function A.new() -- public funcion
......
end
funcion A:print() -- public 'method'
print (self) -- 'self' authomatic parameter
end
end
do -- subproject B
local B = {}
maintable.B = B
............ -- more B things, private and public
end
return maintable
--------------------------------
the trick is to remember that each "do .... end" defines a lexical
scope block, restricting access to local variables. Note that both A
and B are local variables too, but they're made accessible by setting
a field on maintable.
I use this when on a module i have a few related functions that share
some state but the rest of the module doesn't need it. I wrap the
needed local variables and the related functions in a "do .. end"
block inside the module's .lua file.
On bigger projects, each submodule goes on it's own .lua file. No
need for the "do .. end", since each .lua file is a compile chunk, a
lexical scope on itself.
.......... --
--
Javier
- References:
- scope, design patterns?, Patrick Mc(avery
- Re: scope, design patterns?, Tomas Guisasola Gorham
- Re: scope, design patterns?, Patrick Mc(avery
- Re: scope, design patterns?, Sean Conner
- Re: scope, design patterns?, Patrick Mc(avery
- Re: scope, design patterns?, Patrick Mc(avery
- Re: scope, design patterns?, Patrick Mc(avery