Break OO privacy: Difference between revisions

Added Lua.
m (→‎{{header|C sharp}}: Regularize header markup to recommended on category page)
(Added Lua.)
Line 804:
X = 3
true</lang>
 
=={{header|Lua}}==
 
Lua doesn't have a native concept of classes, and the only custom data structure available is the table (in which all fields are always public).
However, it's pretty common for table/object creation functions in object-oriented code to return instances of other functions that uses local variables through lexical scoping, or their closure, which is not accessible to the outside code and could be considered a space with "private" fields.
These can be accessed indirectly through the [https://www.lua.org/manual/5.1/manual.html#5.9 debug library].
 
<lang Lua>local function Counter()
-- These two variables are "private" to this function and can normally
-- only be accessed from within this scope, including by any function
-- created inside here.
local counter = {}
local count = 0
 
function counter:increment()
-- 'count' is an upvalue here and can thus be accessed through the
-- debug library, as long as we have a reference to this function.
count = count + 1
end
 
return counter
end
 
-- Create a counter object and try to access the local 'count' variable.
local counter = Counter()
 
for i = 1, math.huge do
local name, value = debug.getupvalue(counter.increment, i)
if not name then break end -- No more upvalues.
 
if name == "count" then
print("Found 'count', which is "..tostring(value))
-- If the 'counter.increment' function didn't access 'count'
-- directly then we would never get here.
break
end
end</lang>
 
{{out}}
<pre>
Found 'count', which is 0
</pre>
 
Note that there's an infinite number of other more complex ways for functions to store values in a "private" manner, and the introspection functionality of the debug library can only get you so far.
 
=={{header|M2000 Interpreter}}==
Anonymous user