Lua - 从字符串中提取索引值

我有一个 Lua 字符串 s1,如下所示。

s1='..{"login":{"username":"necs_0","url":"sip:192.168.1.218","contact":"sip:necs_0@192.168.1.218:61376","serverip":"192.168.1.216","serverport":"4080"}}';

前两个字节显示为..,其中包含2个字节的大端长度。然后在{"login":{"username":"necs_后面有索引值 0。我需要提取这个索引值。

我编写了下面的脚本,它有效。我想知道编写它的最佳有效方式是什么。

s1='..{"login":{"username":"necs_0","url":"sip:192.168.1.218","contact":"sip:necs_0@192.168.1.218:61376","serverip":"192.168.1.216","serverport":"4080"}}';

-- 高级第一个两个字节
s2 = s1:sub(3);

-- 找到 necs_ 的索引
index1 = s2:find('necs_', 1, true);

-- 找到 " 的索引
index2 = s2:find('"', index1, true);

-- 提取 necs_ 和 " 之间的数据
s3=string.sub(s2,index1+5,index2-1);

-- 打印提取的数据
print(s3)

有几件事情让我担忧,在s2 = s1:sub(3)行中,创建了一个新的字符串 s2,并将 s1 的内容复制到了新的字符串 s2 中。在 C 中,我可以像s2 = s1 + 2那样做,从而可以避免复制。

然后我使用findsub Api。是否有更好的有效选项来完成它呢?

点赞