lua-users home
lua-l archive

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


Kurt Nordstrom wrote:
One of my concerns here is security.  I want the master object to be able
to arbitrarily call the game objects, but I don't want the game objects to
be able to see or affect the master object.  Can anybody suggest a good
way of doing this?  One possibility I thought was to possibly give all of
the game objects a different environment, in which the master object would
not be a part of.  The other would be to enact some sort of privacy scheme
using closures like detailed in the Programming in Lua book.

If you just plan on having the one object, closures are the obvious choice. Just make sure the debug library isn't accessible, or at least not the debug.getupvalue / debug.setupvalue functions.

Closures are the obvious choice because, if you only have one object, you can simply do this:

mysuperobject = {}

do
 local privatetable = {}
 local privatevar
 function mysuperobject:func1()
   -- "public" variables / methods etc are simply
   mysuperobject.var1 = 1
   -- (or, if you're using the method syntax)
   self.var = 1
 end
 function mysuperobject:func2()
   -- "private" variables / methods can be accessed through upvalues, ie
   privatestate.var1 = 1
   privatevar = 1
-- whether you keep all variables inside one "state" table or as a bunch of non-locals is up to you
 end
end

-- After this end, none of the locals inside the do..end block can be modified except for through function calls

It's ideal if you're planning on creating the object only once, as there's no need to share private states between multiple objects or create dozens of closures repeatedly.

Note, people can still modify mysuperobject, ie mysuperobject.func1 = nil.

- Alex