如何确定代码是否作为脚本或函数执行? [英] How to determine if code is executing as a script or function?

查看:160
本文介绍了如何确定代码是否作为脚本或函数执行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您是否可以在运行时确定执行的代码是作为函数还是脚本运行?如果是,推荐的方法是什么?

解决方案

+1一个非常有趣的问题。



我可以想到一种确定方式。解析执行的m文件本身并检查第一个非平凡的非注释行中的第一个单词。如果它是函数关键字,它是一个函数文件。如果不是,它是一个脚本。
这是一个整洁的单行:

  strcmp(textread([mfilename'.m'],'%s ',1,'commentstyle','matlab'),'function')

结果值应该如果它是一个函数文件,则为1,如果是脚本,则为0。



请记住,该代码需要从有问题的m文件中运行,而不是当然,从一个单独的功能文件。如果你想做一个通用的函数( ie 测试任何m文件),只需将所需的文件名字符串传递给 textread ,像这样:

 函数y = isfunction(x)
y = strcmp(textread([x' '],'%s',1,'commentstyle','matlab'),'function')

为了使此功能更加强大,您还可以添加错误处理代码,以验证m文件实际存在,然后再尝试 textread


Can you determine at runtime if the executed code is running as a function or a script? If yes, what is the recommended method?

解决方案

+1 for a very interesting question.

I can think of a way of determining that. Parse the executed m-file itself and check the first word in the first non-trivial non-comment line. If it's the function keyword, it's a function file. If it's not, it's a script. Here's a neat one-liner:

strcmp(textread([mfilename '.m'], '%s', 1, 'commentstyle', 'matlab'), 'function')

The resulting value should be 1 if it's a function file, and 0 if it's a script.

Keep in mind that this code needs to be run from the m-file in question, and not from a separate function file, of course. If you want to make a generic function out of that (i.e one that tests any m-file), just pass the desired file name string to textread, like so:

function y = isfunction(x)
    y = strcmp(textread([x '.m'], '%s', 1, 'commentstyle', 'matlab'), 'function')

To make this function more robust, you can also add error-handling code that verifies that the m-file actually exists before attempting to textread it.

这篇关于如何确定代码是否作为脚本或函数执行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆