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!
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")
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)
精彩评论