[Date Prev][Date Next][Thread Prev][Thread Next]
[Date Index]
[Thread Index]
- Subject: Re: scope, design patterns?
- From: Sean Conner <sean@...>
- Date: Mon, 27 Dec 2010 22:08:43 -0500
It was thus said that the Great Patrick Mc(avery once stated:
> Sorry about the non-sense code I posted earlier, clearly I don't
> understand nested tables and/or how to define them local to their parent
> table and should have tested it before posting.
>
> This code works and I don't actually want mainLoop.library1.z to return
> true.
>
> local mainLoop = {}
> mainLoop.library1 = {}
> mainLoop.library2 = {}
> mainLoop.library1.x = 1
> mainLoop.library2.y = 2
> mainLoop.library1.z = mainLoop.library2.y
> print(mainLoop.library1.z)
> -->2 --wish it returned nil
>
> Sean Conner's code used Meta tables:
> ""
> local dns = org.conman.dns
> local debug = setmetatable(org.conman.debug , { __index = _G.debug })
> local string = setmetatable(org.conman.string , { __index = _G.string })
> """
>
> Is there a way to have nested tables that do not have access to each
> other? Is this why Sean needed to use meta tables?
The nested tables are there to control a namespace, and the use of the
metatables is to gain access to functions from the standard Lua set. I'm
not trying to make private anything, but to control what is included and to
keep the global namespace pollution to a minimum.
For example, I include my table routines:
[spc]lucy:~>lua
Lua 5.1.4 Copyright (C) 1994-2008 Lua.org, PUC-Rio
> tab = require "org.conman.table"
> tab.show(tab)
show function: 0x8774f08
_M table: 0x87760b8
_NAME "org.conman.table"
_PACKAGE "org.conman."
>
The only function there is show(), which dumps the table out. But if I
were to try to use it as I do table ...
> m = {}
> tab.insert(m,3)
stdin:1: attempt to call field 'insert' (a nil value)
stack traceback:
stdin:1: in main chunk
[C]: ?
>
Obviously, there's no insert() function in tab, so that's expected, but
...
> setmetatable(tab,{__index = table})
> tab.insert(m,3)
> tab.show(m)
1 3
> tab.show(tab)
show function: 0x8774f08
_M table: 0x87760b8
_NAME "org.conman.table"
_PACKAGE "org.conman."
>
By using the metatable, I can include the standard Lua table functions
with my "table" extentions. In fact, it can be done in one statement:
local tab = setmetatable(require(org.conman.table),{__index = table})
which doesn't pollute the default Lua table with functions, and allows my
code to use table functions I'm acustomed to. If this is making any sense.
-spc
- 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