OddCore
OddCore

Reputation: 1584

Regular expressions in Lua using .gsub()

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!

Upvotes: 6

Views: 14071

Answers (2)

lhf
lhf

Reputation: 72312

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)

Upvotes: 3

Joey
Joey

Reputation: 354456

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

Upvotes: 5

Related Questions