首页 > 解决方案 > lua 中 source:match("%d*") 的含义是什么?

问题描述

-- Parse speed value as kilometers by hours.
function Measure.parse_value_speed(source)
  local n = tonumber(source:match("%d*"))
  if n then
    if string.match(source, "mph") or string.match(source, "mp/h") then
      n = n * miles_to_kilometers
    end
    return n
  end
end

我对上面代码中 %d 之后的“*”感到困惑。任何意见都非常感谢。

标签: lua

解决方案


这一切都在 Lua 参考手册中!

source:match("%d*")

是语法糖吗string.match(source, "%d*")

https://www.lua.org/manual/5.3/manual.html#3.4.10

string.match(s, pattern [, init])在字符串 s 中查找 pattern 的第一个匹配项(参见§6.4.1 )。如果找到,则 match 从模式中返回捕获;否则返回零。如果 pattern 指定没有捕获,则返回整个匹配。第三个可选的数字参数 init 指定从哪里开始搜索;它的默认值为 1,可以为负数。


推荐阅读