lua-users home
lua-l archive

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


On 1 April 2012 01:08, Jose Torre-Bueno <jtorrebueno@cox.net> wrote:
This tells me that there is a single upvalue fvar that is shared by g() and h().  I assume it will persist until both g() and h() go out of scope.  It is also not visible outside of g() or h().  I also notice that f = nil does not cause fvar to disappear nor does setting g to nil.

Yes, that upvalue is shared by both functions, because they were created in the scope of the same local variable.
 
Out of curiosity is there any way to access or change an upvalue like fvar outside of any functions that own pointers to it?

Only using the debug interface: http://www.lua.org/pil/23.1.2.html
 
It appears to me that if not upvalues  would be a useful way to have private variables in objects.  An object generating function could create the storage for private variables and the method functions and then return a table of methods which was the object.  Since the private data was an upvalue of the method functions it would be accessible only through them.

That's exactly the way you would do it if you wanted to achieve privacy. There is even a section about it in Programming in Lua [1]. You can even use upvalues to create sandboxes/wrappers which keep a private reference to the original function [2].

[1] http://www.lua.org/pil/16.4.html
[2] http://www.lua.org/pil/6.1.html