Polymorphic copy: Difference between revisions

→‎{{header|Lua}}: added Lua solution
m (→‎{{header|Phix}}: added syntax colouring the hard way)
(→‎{{header|Lua}}: added Lua solution)
Line 1,309:
Dog 'a' is not the same object as Dog 'b'
</pre>
 
=={{header|Lua}}==
Lua does not have any formal notion of OOP principles, however there are numerous ways to build work-alikes. The basic data type for building OOP-like systems is the <code>table</code>, which are easily copied (a shallow copy suffices for this task), and easily assigned (dynamically typed). The "prototype approach" (rather than the "metamethod approach") to OOP-like seems to better illustrate the task, so here such a system is built incrementally. One method will be overridden (per task), and one inherited (stretch), to better demonstrate that part of the original copy still remains while another part was modified:
<lang lua>T = { name=function(s) return "T" end, tostring=function(s) return "I am a "..s:name() end }
 
function clone(s) local t={} for k,v in pairs(s) do t[k]=v end return t end
S1 = clone(T) S1.name=function(s) return "S1" end
 
function merge(s,t) for k,v in pairs(t) do s[k]=v end return s end
S2 = merge(clone(T), {name=function(s) return "S2" end})
 
function prototype(base,mixin) return merge(merge(clone(base),mixin),{prototype=base}) end
S3 = prototype(T, {name=function(s) return "S3" end})
 
print("T : "..T:tostring())
print("S1: " ..S1:tostring())
print("S2: " ..S2:tostring())
print("S3: " ..S3:tostring())
print("S3's parent: "..S3.prototype:tostring())</lang>
{{out}}
<pre>T : I am a T
S1: I am a S1
S2: I am a S2
S3: I am a S3
S3's parent: I am a T</pre>
 
=={{header|MiniScript}}==
Anonymous user