[erlang-questions] Question about record_info

Ladislav Lenart lenartlad@REDACTED
Mon Jan 8 14:03:30 CET 2007


Daniel Luna wrote:
> On Mon, 8 Jan 2007, Ladislav Lenart wrote:
>> How can I obtain info about a record given its name?
>> For example let's suppose I have an obligate person
>> record with fields: name, phone and address. I would
>> like to be able to do the following:
>> record_info(fields, person) %% -> {name, phone, address}
>>
>> The following is what the reference manual says about the
>> topic (section 8.7 Internal Representation of Records):
>>
>> ----------------------------------------------------------------
>> To each module using records, a pseudo function is added
>> during compilation to obtain information about records:
>>
>> record_info(fields, Record) -> [Field]
>> record_info(size, Record) -> Size
>>
>> Size is the size of the tuple representation, that is one
>> more than the number of fields.
>> ----------------------------------------------------------------
>>
>> But whatever I try, I get either:
>>  * undef for record_info function,
>>  * illegal record info,
>>  * record Name undefined.
> 
> record_info is not a proper function. It only exists during compilation, 
> which means that it cannot take variable arguments.
> 
> record_info(fields, address) %% works
> 
> Rec = address,
> record_info(fields, Rec) %% doesn't work!
> 
> Of course it only works if the address record is defined in that module.
> 
> If you do want a function that uses record_info, try to use a macro 
> instead.
> 
> This will work:
> 
> -define(print_fields(Rec), io:format("~p~n", [record_info(fields, Rec)])).
> 
> And then use: ?print_fields(address)
> 
> This will not work:
> 
> print_fields(Rec) ->
>   io:format("~p~n", [record_info(fields, Rec)]).
> 
> 
> So you need two things:
> 
> 1. the record needs to be defined in the module where you use 
> record_info (through an -include or through -record).
> 
> 2. The argument to record_info needs to be an 'atom' and not a Variable.

Thank you, I finally managed to make it work. My problem was that I
didn't know that record_info is not a normal function. I thought that
it is automatically compiled to each module that uses records and not
that it only exists during compilation of the module.

Thanks again,

Ladislav Lenart





More information about the erlang-questions mailing list