lua-users home
lua-l archive

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


Eero Pajarre wrote:

> This is powerfull stuff....
> (Were upvalues read-only?)
> 
> Btw. I became curious about what Peter had suggested
> year ago. I think that what he wanted (protected datatypes
> in Lua) might be implementable with closures. Create an object
> which has its internals in a closure, which can only be
> accessed by the interface functions, hmmm, I don't know if there
> are any holes here.
> 
>                 Eero

You mean something like this?

myobject = {};

function myobject:init()
  local x , y , w , h,  string = 5, 5, 20, 10, "Hello"
  -- the "private" variables of the object  
  self.getx = (function(self) return x; end)
  -- Add a get method
  self.setx = 
  ( function(self, val) 
      if val < 0 then 
        print("X must be greater than 0") 
        else x = val; 
      end 
    end 
  )
  -- And add a set method.
  self.print = 
  ( function(self)
      print(x,y,h,w,string); 
    end 
  )
end

myobject:init() -- prepare object for use.
myobject:print();
myobject:setx(-10); -- Will refuse to do it.
myobject:print(); -- still the same
myobject:setx(20); -- OK
print(myobject:getx()) -- OK, will print 20
for k,v in pairs(myobject) do print(k,v); end
-- But we can't get the variables directly.
-- Unless we use debug or such.


Note that apart from using this methos, you could
also do something similar with the getglobals() and 
setglobals() function.

-- 
"No one knows true heroes, for they speak not of their greatness." -- 
Daniel Remar.
Björn De Meyer 
bjorn.demeyer@pandora.be