shell – Torch,如何用“dofile”和输入参数执行脚本?

前端之家收集整理的这篇文章主要介绍了shell – Torch,如何用“dofile”和输入参数执行脚本?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我正在使用th命令从我的 Linux shell执行Torch脚本.这个Torch脚本有两个输入参数:

th torch_script.lua input_parameter1 input_parameter2

现在我想通过Torch shell运行这个脚本.为此,我必须使用dofile命令.但在这种情况下,我不知道如何传递输入参数input_parameter1和input_parameter2.

在Torch中,如何将一些输入参数传递给dofile执行命令?

编辑:这是我正在尝试运行的代码.我无法正常运行,也许你可以告诉我原因

external_command.lua内容

  1. local arg = arg or {...}
  2. input_parameter = arg[1]
  3. print("input_parameter ".. input_parameter);

在shell上:

  1. $th
  2. th> tempFunc = load "external_command.lua"
  3. th> tempFunc("try")
  4. [string "_RESULT={tempFunc("try")}"]:1: attempt to call global 'tempFunc' (a nil value)
  5. stack traceback:
  6. [string "_RESULT={tempFunc("try")}"]:1: in main chunk
  7. [C]: in function 'xpcall'
  8. /home/davide/torch/install/share/lua/5.1/trepl/init.lua:630: in function 'repl'
  9. ...vide/torch/install/lib/luarocks/rocks/trepl/scm-1/bin/th:185: in main chunk
  10. [C]: at 0x004064d0

编辑2:我尝试了TonyHsu发布的解决方案,但无论如何它都无法正常工作.
这就是我正在做的事情.

我在名为runfile.lua的脚本中定义了一个函数runfile(),其中包含以下代码

  1. function runfile(scriptName,input)
  2. opt = nil
  3. arg = input
  4. dofile(scriptName)
  5. end

然后我使用我之前为此函数定义为scriptName输入参数的external_command.lua脚本:

  1. th> scriptName = "external_command.lua"
  2. th> require './runfile.lua'
  3. th> runfile(scriptName,"Hello world");

不幸的是,在这种情况下,我收到一个错误

  1. external_command.lua:4: attempt to concatenate global 'input_parameter' (a nil value)
  2. stack traceback:
  3. external_command.lua:4: in main chunk
  4. [C]: in function 'dofile'
  5. /home/davide/torch/temp/runfile.lua:4: in function 'runfile'
  6. [string "runfile(scriptName,"Hello world");"]:1: in main chunk
  7. [C]: in function 'xpcall'
  8. /home/davide/torch/install/share/lua/5.1/trepl/init.lua:648: in function 'repl'
  9. ...vide/torch/install/lib/luarocks/rocks/trepl/scm-1/bin/th:185: in main chunk
  10. [C]: at 0x004064d0
我认为诀窍是传递全局变量’args’中的参数.说,我在external_command.lua中有以下内容.
  1. -- args has been set by the caller
  2. if not args or #args == 0 then
  3. print('no input_parameter')
  4. else
  5. print('#args = ' .. #args,'input_parameter: ' .. args[1])
  6. end

然后按如下方式定义runfile().

  1. function runfile(f,...)
  2. local tmp = args -- save the original global args
  3. args = table.pack(...)
  4. dofile(f)
  5. args = tmp -- restore args
  6. end

我已经测试了它.看起来像这样.

  1. th> runfile('ext_command.lua',10)
  2. #args = 1 input_parameter: 10
  3. [0.0002s]
  4. th> runfile('ext_command.lua','a','b','c')
  5. #args = 3 input_parameter: a
  6. [0.0002s]

猜你在找的Bash相关文章