Avoiding eval when overloading a function

5 visualizaciones (últimos 30 días)
Daniel Shub
Daniel Shub el 29 de Ag. de 2012
I used eval in this answer where I was trying to overload display and it is making me feel sick. Is it possible to avoid the eval? A simple example is overloading display to prepend a string to object of class char ...
If you add the following function to a folder called @char
function display(X)
X = ['The string: ', X];
eval([inputname(1), ' = X;']);
eval(['builtin(''display'', ', inputname(1), ');']);
end
and then do
>> z = 'Hello world'
z =
The string: Hello world
I need the eval to get the variable name correct in the output. The documentation for display shows a work around where you recreate the functionality of the built-in display, but that is more distasteful to me than eval. Is it possible to overload display to do some preprocessing and then hand off the result to the built-in display without using eval
EDIT
My simplification has apparently confused people. In this question Jonathan essentially noted that
>> str = '<test TEST>'
returns
str =
TEST
but he wanted it to return
str =
<test TEST>
I suggested an answer which overloaded display in a manner analogous to my simplification above.
  1 comentario
Jan
Jan el 29 de Ag. de 2012
+1: My favorite question of the week, because it uses trivial commands to dig in the underground of the Matlab interpreter.

Iniciar sesión para comentar.

Respuestas (2)

Jan
Jan el 29 de Ag. de 2012
I do not get the problem. Would this be useful:
function display(X)
Name = inputname(1);
if ~isempty(Name)
localAssignName(Name, X);
builtin('display', Name);
end
end
function localAssignName(Name, Data)
assignin('caller', Name, ['The string: ', Data]);
end
I cannot test this currently. How does the output differ from your expectations?
  3 comentarios
Jan
Jan el 29 de Ag. de 2012
Then let me apply a subterfuge: Why on earth do you need such a strange function?!
I'll take a look into the source of DISPLAY in the evening. Obviously it uses inputname itself, such that my approach must fail. What happens with your method, when the variable is called "inputname" or "builtin"?
Daniel Shub
Daniel Shub el 29 de Ag. de 2012
The original question that I was answering, which addressed a problem that I have had in the past, is how to display a variable which contains an HTML string. The DISPLAY function is built-in so you cannot see the code. Using poorly named variables causes problems.

Iniciar sesión para comentar.


Sean de Wolski
Sean de Wolski el 29 de Ag. de 2012
Editada: Sean de Wolski el 29 de Ag. de 2012
Perhaps (probably) I'm missing something, but could you just use fprintf?

Categorías

Más información sobre Variables en Help Center y File Exchange.

Etiquetas

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by