lua-users home
lua-l archive

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


local _M = {}
-- stolen from: https://github.com/kikito/middleclass/wiki/Private-stuff
local _private = setmetatable({}, {__mode = "k"})

--constructor
function _M:new(...)
   local object = {}
   -- do stuff

   _private[object].privateField = 1
   return object
end

2011/4/29 Emmanuel Oga <emmanueloga@gmail.com>
>
> On Fri, Apr 29, 2011 at 1:13 AM, Lorenzo Donati
> <lorenzodonatibz@interfree.it> wrote:
> > On 28/04/2011 16.12, Mark Hamburg wrote:
> >>
> >> If your goal is keeping clients from accidentally messing with state, then
> >> you can often deal with this with simple naming conventions -- e.g., private
> >> fields start with _ or priv_ or whatever.
> >>
> >> If you are a little more paranoid and can live with somewhat more typing
> >> and a loss in debugger support (or a need for a more sophisticated
> >> debugger), then define private keys using tables:
> >>
> >>        local keyMyPrivateField = {}
> >>
> >>        self[ keyMyPrivateField ] = 'can't see this'
> >>
> >> If you never give out the keys, then clients can't mess with the field
> >> contents.
> >>
> >> Except, of course, they can if they use pairs or next to iterate the table
> >> and recover them. So, that's where you have to decide whether you are
> >> concerned with sloppy coding or mischievous coding.
> >
> > Ouch (*big slap on forehead*)! I didn't consider that!
> > I knew I could iterate the proxy, but somehow my brain ruled that out
> > automatically! Here is a big gotcha of my approach! I'm giving out the
> > metatable to anyone who might iterate my proxies (so the whole point of
> > keeping it private is moot)!
> >
> > Well, as I said I don't need strict access control, only - perhaps - robust
> > data hiding, so I don't think of banning next, pairs, etc, from the client
> > code. Therefore probably the simpler and best approach is to stick to a
> > simple naming convention for the private data, as you suggested:
> >
> > local proxy = {}
> > proxy._obj = {} -- private data
> >
> > I wonder if a better crafted newproxy function could help here. I read in
> > the archive that Lua team considered it not robust enough to give it
> > support, and with upcoming 5.2 it is going to be removed.
> > (I never used it actually - I don't like to depend on undocumented
> > features).
> >
>
> For data hiding you could consider too saving the private data on a closure:
>
> function Object()
>  local new = {key="PUBLIC"}
>  local private = {key="PRIVATE"}
>
>  new.method = function()
>    print(private.key, new.key)
>  end
>
>  return new
> end
>
> new = Object()
> new.method()
>
>
> --------------------------------------------------------------
> EmmanuelOga.com - Software Developer
>
>
> > Thank you very much Mark
> >
> > --
> > Lorenzo
> >
> >
> >
>



--
Łukasz Gruner