string.find使用Lua中的目录路径

时间:2010-07-07 10:07:54

标签: perl string lua

我需要将这段代码从Perl翻译成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")

现在,当我尝试编译时,我得到关于代码第二行的以下错误

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

很明显,在string.find中使用目录路径的语法与我编写它的方式不同。 “不管怎么样?”是我的问题。

2 个答案:

答案 0 :(得分: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)

答案 1 :(得分: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

之后无需关闭文件。