简体   繁体   中英

How invoke a function given its name in string in Lua/Torch?

I want to evaluate a string name as a function in Lua/Torch. Below is an example of what I want to do:

require 'torch'

tensorType = torch.getdefaulttensortype()
print (tensorType) -- Will print "torch.DoubleTensor"

My goal is to be able to use the string in tensorType as name of a function and evaluate that function like follow:

tensorType(some arguments)

In MATLAB and Python there is a `eval()' function which can execute arbitrary strings. Is there such a function in Lua/Torch?

How can I do that in Torch/Lua?

You can use loadstring but that's generally not recommended because it has to compile code at runtime. What is this for?

First extract the name of the field from the string:

k=tensorType:match("%.(.+)$")

Then use the name to call the function:

torch[k](some arguments)

You could also try lutorpy , you will have a lua engine in python, thus, you can load any lua/torch library, and you can run lua code with "lua.eval('torch.DoubleTensor(3,4)')". Check lutorpy for more details.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM