在(old) Lua中进行字符串token化

我正在尝试使用Lua对NMEA语句进行tokenization。目前可用的Lua版本(可在https://www.lua.org/cgi-bin/demo 上下载)正常工作:

local index = 0
for token in string.gmatch("$HEHDT,99.00,,T*2F", "[%w.]*") do
 print(string.format("%d: %s", index, token))
 index = index + 1
end

输出为:

0:
1: HEHDT
2: 99.00
3:
4: T
5: 2F
您的程序运行成功。

然而,在Lua 5.1.4(以及Wireshark中的5.2.4)中使用时:

0:
1: HEHDT
2:
3: 99.00
4:
5:
6: T
7:
8: 2F
9:

是否有一种方法可以在旧版本的Lua中实现与使用当前版本相同的tokenization输出?

点赞
用户4984564
用户4984564

看起来 Lua 会将两个令牌之间的空字符串识别为单独的令牌,原因不明。这很不直观,但并非完全错误,因为 [%w]* 可以匹配空字符串。你可以通过使用 string.find 并在每次匹配后递增位置两个字符而不是一个来解决此问题:

local index = 0
local str = "$HEHDT,99.00,,T*2F"

local a, b = 0, 1
while true do
  a, b = str:find("[%w.]*", b+2)
  if not a then break end
  print(string.format("%d: [%i,%i] %s", index, a, b, str:sub(a, b)))
  index = index + 1
end

这段代码可能可以改写得更漂亮,但我就留给你们自己想象一下了:D

2020-03-05 12:24:56
用户1847592
用户1847592
```lua
local index = 0
local str = "$HEHDT,99.00,,T*2F"
for token in string.gmatch(str.."$", "([%w.]*)[^%w.]") do
   print(string.format("%d: %s", index, token))
   index = index + 1
end

```lua
local index = 0
local str = "$HEHDT,99.00,,T*2F"
for token in string.gmatch(str.."$", "([%w.]*)[^%w.]") do
   print(string.format("%d: %s", index, token))
   index = index + 1
end
2020-03-05 12:28:29