2010-07-07 71 views
0

目錄路徑我需要這段代碼轉換在Perl到Lua使用Lua中

open(FILE, '/proc/meminfo'); 
while(<FILE>) 
{ 
    if (m/MemTotal/) 
    { 
     $mem = $_; 
     $mem =~ s/.*:(.*)/$1/; 
    } 
    elseif (m/MemFree/) 
    { 
     $memfree = $_; 
     $memfree =~ s/.*:(.*)/$1/; 
    } 
} 
close(FILE); 

到目前爲止,我已經寫了這個

while assert(io.open("/proc/meminfo", "r")) do 
    Currentline = string.find(/proc/meminfo, "m/MemTotal") 
    if Currentline = m/MemTotal then 
     Mem = Currentline 
     Mem = string.gsub(Mem, ".*", "(.*)", 1) 
    elseif m/MemFree then 
     Memfree = Currentline 
     Memfree = string.gsub(Memfree, ".*", "(.*)", 1) 
    end 
end 
io.close("/proc/meminfo") 

現在string.find,當我嘗試編譯,我得到以下錯誤關於我的代碼

luac: Perl to Lua:122: unexpected symbol near '/' 

第二行顯然使用STR的目錄路徑的語法ing.find不像我寫的那樣。 「但是它怎麼樣?」是我的問題。

回答

1

要逐行迭代文件,可以使用io.lines

for line in io.lines("/proc/meminfo") do 
    if line:find("MemTotal") then --// Syntactic sugar for string.find(line, "MemTotal") 
     --// If logic here... 
    elseif --// I don't quite understand this part in your code. 
    end 
end 

之後無需關閉文件。

+0

非常感謝你 – OddCore 2010-07-07 10:43:48

+0

很高興爲您提供幫助。如果你打算在Lua進一步編碼,我建議你閱讀Lua的Programming,它的第一版可以在http://www.lua.org/pil/免費在線獲得。 – ponzao 2010-07-07 11:33:48

+0

我擁有由k.Jung和A.Brown撰寫的Beggining Lua Programming,這本書是我在教科書中看到的最好的索引。麻煩的是,在我負責將大約300行Perl語言翻譯成Lua之前,我從來沒有完成過其中的任何一個,所以我正在並行地學習它們。 – OddCore 2010-07-08 07:40:07

2

你不必堅持Perl的控制流程。 Lua有一個非常不錯的「gmatch」函數,它允許你遍歷字符串中所有可能的匹配。這是一個解析/ proc/meminfo並將其作爲表格返回的函數:

function get_meminfo(fn) 
    local r={} 
    local f=assert(io.open(fn,"r")) 
    -- read the whole file into s 
    local s=f:read("*a") 
    -- now enumerate all occurances of "SomeName: SomeValue" 
    -- and assign the text of SomeName and SomeValue to k and v 
    for k,v in string.gmatch(s,"(%w+): *(%d+)") do 
      -- Save into table: 
     r[k]=v 
    end 
    f:close() 
    return r 
end 
-- use it 
m=get_meminfo("/proc/meminfo") 
print(m.MemTotal, m.MemFree)