Add a variable to a class instance at runtime: Difference between revisions
Content added Content deleted
(→{{header|Io}}: Added description about the process) |
|||
Line 118: | Line 118: | ||
CL-USER 62 > (slot-value *an-instance* 'slot1) |
CL-USER 62 > (slot-value *an-instance* 'slot1) |
||
23</pre> |
23</pre> |
||
=={{header|D}}== |
|||
D is a statically compiled language, so there are some limits. |
|||
This adds a new 'attribute' to a struct/class instance, of type T: |
|||
<lang d>import std.stdio: writeln; |
|||
import std.traits: isImplicitlyConvertible; |
|||
struct S(T) { |
|||
T[string] data; |
|||
template opDispatch(string name) { |
|||
T opDispatch(Types...)(Types args) |
|||
if (!args.length || (args.length == 1 && isImplicitlyConvertible!(Types[0],T))) { |
|||
static if (args.length) { |
|||
data[name] = args[0]; |
|||
return args[0]; |
|||
} else |
|||
return data[name]; |
|||
} |
|||
} |
|||
} |
|||
void main() { |
|||
S!long s; |
|||
s.foo = 1; |
|||
writeln(s.foo()); |
|||
}</lang> |
|||
If the attribute name is not known at compile-time, you have to use a more normal syntax: |
|||
<lang d>import std.stdio: writeln; |
|||
struct S(T) { |
|||
T[string] data; |
|||
alias data this; |
|||
} |
|||
void main() { |
|||
S!long s; |
|||
string name = "bar"; |
|||
s[name] = 2; |
|||
writeln(s[name]); |
|||
}</lang> |
|||
If the type is variable it can be used an associative array of variants, but things become more complex. Adding a name to all instances of a class can be possible. |
|||
=={{header|Falcon}}== |
=={{header|Falcon}}== |