【问题标题】:string.find using directory path in Luastring.find 在 Lua 中使用目录路径
【发布时间】:2011-03-12 17:56:44
【问题描述】:

我需要把这段代码从 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 中使用目录路径的语法与我编写的方式不同。 “但是怎么样?”是我的问题。

【问题讨论】:

    标签: perl string lua


    【解决方案1】:

    您不必拘泥于 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)
    

    【讨论】:

      【解决方案2】:

      要逐行迭代文件,您可以使用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
      

      之后无需关闭文件。

      【讨论】:

      • 很高兴为您提供帮助。如果您打算进一步使用 Lua 进行编码,我建议您阅读《Lua 编程》,它的第一版可在 lua.org/pil 在线免费获得。
      • 我拥有 k.Jung 和 A.Brown 的 Beggining Lua Programming,这是一本非常好的书,具有我在教科书中看到的最佳索引。麻烦的是,在我负责将大约 300 行 Perl 翻译成 Lua 之前,我从来没有做过任何一个,所以我正在并行学习它们。
      猜你喜欢
      • 1970-01-01
      • 2017-08-08
      • 2021-11-02
      • 2021-01-30
      • 2012-02-23
      • 2014-08-04
      • 2021-01-18
      • 2017-03-01
      • 1970-01-01
      相关资源
      最近更新 更多