views:

159

answers:

2

Hello,

I need to translate this piece of code from Perl to Lua

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

So far I've written this

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")

Now, when I try to compile, I get the following error about the second line of my code

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

obviously the syntax of using a directory path in string.find is not like how I've written it. 'But how is it?' is my question.

+1  A: 

To iterate a file line by line you can use 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

No need to close the file afterwards.

ponzao
Thank you very much
OddCore
Glad to help. If you're planning on coding in Lua further I recommend reading Programming in Lua, its first edition is available free online at http://www.lua.org/pil/.
ponzao
I am in possession of Beggining Lua Programming by k.Jung and A.Brown, which is a very good book with the best index I have seen in a textbook. Trouble is, before I was tasked with translating about 300 lines of Perl to Lua, I had never done either of them, so I'm learning them both in parallel.
OddCore
Ok that sounds crazy :)
ponzao
+1  A: 

You don't have to stick to Perl's control flow. Lua has a very nice "gmatch" function which allows you to iterate over all possible matches in a string. Here's a function which parses /proc/meminfo and returns it as a table:

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)
Luther Blissett