更新时间:2024-01-22 10:51
eval() 函数可将字符串转换为代码执行,并返回一个或多个值
返回值 = eval( codeString )
如果eval函数在执行时遇到错误,则抛出异常给调用者.
类似的函数是loadcode ,loadcode并不立即执行代码,而是返回一个函数对象.
并且loadcode支持路径参数,eval并不支持. eval并不支持代码中的return语句,而是将代码作为表达式直接计算出结果.
alert(d.name);
Execute string containing MATLAB expression
eval(expression)
[a1, a2, a3, ...] = eval('myfun(b1, b2, b3, ...)')
eval(expression) executes expression, a string containing any valid MATLAB expression. You can construct expression by concatenating substrings and variables inside square brackets:
[a1, a2, a3, ...] = eval('myfun(b1, b2, b3, ...)') executes function smyfun with arguments b1, b2, b3, ..., and returns the results in the specified output variables.
Using the eval output argument list is recommended over including the output arguments in the expression string. The first syntax below avoids strict checking by the MATLAB parser and can produce untrapped errors and other unexpected behavior. Use the second syntax instead:
% Not recommended
eval('[a1, a2, a3, ...] = function(var)')
% Recommended syntax
[a1, a2, a3, ...] = eval('function(var)')
Example 1 – Working with a Series of Files
Load MAT-files August1.mat to August10.mat into the MATLAB workspace:
for d=1:10
s = ['load August' int2str(d) '.mat']
eval(s)
end
These are the strings being evaluated:
s =
load August1.mat
s =
load August2.mat
s =
load August3.mat
- etc. -
Example 2 – Assigning to Variables with Generated Names
Generate variable names that are unique in the MATLAB workspace and assign a value to each using eval:
for k = 1:5
t = clock;
pause(uint8(rand * 10));
v = genvarname('time_elapsed', who);
eval([v ' = etime(clock,t)'])
end
As this code runs, eval creates a unique statement for each assignment:
time_elapsed =
5.0070
time_elapsed1 =
2.0030
time_elapsed2 =
7.0010
time_elapsed3 =
8.0010
time_elapsed4 =
3.0040
Example 3 – Evaluating a Returned Function Name
The following command removes a figure by evaluating its CloseRequestFcn property as returned by get.
eval(get(h,'CloseRequestFcn'))
Eval函数在PHP代码中的使用:eval() 函数把字符串按照 PHP 代码来计算。该字符串必须是合法的 PHP 代码,且必须以分号结尾。如果没有在代码字符串中调用 return 语句,则返回 NULL。如果代码中存在解析错误,则 eval() 函数返回 false。
Eval函数在VBScript脚本语言中的使用: 在VB脚本语言中,Eval函数具有两层意思,一是实现计算表达的值,即eval()函数可将字符串转换为代码执行,并返回一个或多个值;二是运行指定的代码。
eval(expression[, globals[, locals]])
有三个参数,表达式字符串,globals变量作用域,locals变量作用域。 其中第二个和第三个参数是可选的。
如果忽略后面两个参数,则eval在当前作用域执行。
如果指定globals参数
如果指定locals参数
如果要严格限制eval执行,可以设置globals为__builtins__,这样 这个表达式只可以访问__builtin__module。