Runtime evaluation: Difference between revisions

Added MATLAB example
(added zkl)
(Added MATLAB example)
Line 585:
typeof bar; // 'string'
</lang>
 
=={{header|MATLAB}}==
The eval and evalin functions handles any kind of code. It can handle multi-line code, although it needs the lines to be separated by the newline character. It can even allow you to program at runtime, as illustrated in the last example in the code and output below. Errors can occur when mixing eval statements with regular code, especially "compile-time" errors if the code appears to be missing key elements (ending brackets or end statements, etc). Some of these are also demonstrated.
<lang MATLAB>function testEval
fprintf('Expressions:\n')
x = eval('5+10^2')
eval('y = (x-100).*[1 2 3]')
eval('z = strcat(''my'', '' string'')')
try
w eval(' = 45')
catch
fprintf('Runtime error: interpretation of w is a function\n\n')
end
% eval('v') = 5
% Invalid at compile-time as MATLAB interprets as using eval as a variable
fprintf('Other Statements:\n')
nl = sprintf('\n');
eval(['for k = 1:20' nl ...
'fprintf(''%.3f\n'', k)' nl ...
'if k == 3' nl ...
'break' nl ...
'end' nl ...
'end'])
true == eval('1')
try
true eval(' == 1')
catch
fprintf('Runtime error: interpretation of == 1 is of input to true\n\n')
end
fprintf('Programming on the fly:\n')
userIn = true;
codeBlock = '';
while userIn
userIn = input('Enter next line of code: ', 's');
codeBlock = [codeBlock nl userIn];
end
eval(codeBlock)
end</lang>
{{out}}
<pre>Expressions:
 
x =
 
105
 
 
y =
 
5 10 15
 
 
z =
 
my string
 
Runtime error: interpretation of w is a function
 
Other Statements:
1.000
2.000
3.000
 
ans =
 
1
 
Runtime error: interpretation of == 1 is of input to true
 
Programming on the fly:
Enter next line of code: fprintf('Goodbye, World!\n')
Enter next line of code: str = 'Ice and Fire';
Enter next line of code: words = textscan(str, '%s');
Enter next line of code: fprintf('%s ', words{1}{end:-1:1})
Enter next line of code:
Goodbye, World!
Fire and Ice</pre>
 
=={{header|Maxima}}==
 
Anonymous user