views:

44

answers:

2

Ok, I think I overcomplicated things and now I'm lost. Basically, I need to translate this, from Perl to Lua:

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

}
close(FILE);

So far I've written this:

for Line in io.lines("/proc/meminfo") do
    if Line:find("MemTotal") then
        Mem = Line
        Mem = string.gsub(Mem, ".*", ".*", 1)
    end
end

But it is obviously wrong. What am I not getting? I understand why it is wrong, and what it is actually doing and why when I do

print(Mem)

it returns

.*

but I don't understand what is the proper way to do it. Regular expressions confuse me!

+1  A: 

Lua doesn't use regular expressions. See Programming in Lua, sections 20.1 and following to understand how pattern matching and replacement works in Lua and where it differs from regular expressions.

In your case you're replacing the complete string (.*) by the literal string .* – it's no surprise that you're getting just .* returned.

The original regular expression replaced anything containing a colon (.*:(.*)) by the part after the colon, so a similar statement in Lua might be

string.gsub(Mem, ".*:(.*)", "%1")
Joey
ok, thank you. It sort of makes sense now, I just think I will never be able to fully comprehend regular expressions.
OddCore
The capture group (`(.*)`) is unnecessary. `string.gsub(Mem, ".*:", "")` is enough. It removes everything up to the last `:`.
MizardX
@Mizard: I just copied the code verbatim from the Perl code, but indeed this should suffice, yes.
Joey
+1  A: 

The code below parses the contents of that file and puts it in a table:

meminfo={}
for Line in io.lines("/proc/meminfo") do
    local k,v=Line:match("(.-): *(%d+)")
    if k~=nil and v~=nil then meminfo[k]=tonumber(v) end
end

You can then just do

print(meminfo.MemTotal)
lhf
This is a much better and more complete solution.
daurnimator