将文件参数传递给Lua中的脚本

时间:2014-02-16 17:16:21

标签: file-io lua

我需要读取一个我不知道的输入文件。

我知道在C中我们可以这样做:

FILE *Ifile;
File *Ofile;

int main(int argc, char *argv[]){

    // Input and Output files
    Ifile = fopen(argv[1],"r");
    Ofile = fopen(argv[2],"w");

  (More code)
}

然后调用“./cprogram <any file name>.txt <any file name>.txt

我可以用.Lua脚本做这样的事吗?

1 个答案:

答案 0 :(得分:3)

是的,你可以。来自documentation

  

在开始运行脚本之前,lua在名为arg的全局表中收集命令行中的所有参数。脚本名称存储在索引0,脚本名称转到索引1后的第一个参数,依此类推。

例如,您可以执行以下操作:

if #arg < 2 then
    print ("usage: lua " .. arg[0] .. " <ifile> <ofile>")
    return
end

local ifile = io.open(arg[1], "r")
local ofile = io.open(arg[2], "w")
if not ifile or not ofile then
    print ("Error: could not open files")
    return
end