2010-07-07 36 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)