[erlang-questions] Dynamically access record fields

David Cartt dcartt@REDACTED
Tue Feb 12 03:35:15 CET 2013


You could use record_info(fields, Record) to get an ordered list of the
record fields and use that to find the tuple index of the requested field.
 Although the fields are returned in order, the documentation does not
specify that as far as I've seen, only that it returns a list of the
fields.  A nasty bug would result if in a future release it stopped
returning the fields in order, or even better, if for some records or in
some situations it didn't return the fields in order.  Hard coding your own
field index table would get around this potential problem.

Here's an example:

-record(r, {r1="1", r2="2", r3="3"}).
t(F, NewV) ->
    R = #r{},
    OldV = get_value(F, R),
    R1 = set_value(F, R, NewV),
    ?debugFmt("R=~p, R1=~p, Old=~p",[R, R1, OldV]).

get_value(F, R)    -> element(field_index(F), R).
set_value(F, R, V) -> setelement(field_index(F), R, V).

field_index(F) -> index(F, record_info(fields, r), 2).

index(M, [M|_], I) -> I;
index(M, [_|T], I) -> index(M, T, I+1).


Calling:

t(r1, new)

prints out:

R={r,"1","2","3"}, R1={r,new,"2","3"}, Old="1"
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://erlang.org/pipermail/erlang-questions/attachments/20130211/e07682b2/attachment.htm>


More information about the erlang-questions mailing list