2014-02-16 62 views
1

我需要讀取一個我不知道的名稱的輸入文件。將文件參數傳遞給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腳本?

+0

的Lua腳本的命令行參數可爲'ARG [1]','ARG [2]',... –

回答

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