如何在声明后访问 ProtoField 的名称?

我如何在声明 ProtoField 后访问其名称?

例如,类似于以下内容:

myproto = Proto("myproto", "My Proto")

myproto.fields.foo = ProtoField.int8("myproto.foo", "Foo", base.DEC)

print(myproto.fields.foo.name)

我得到输出:

Foo

点赞
用户3138095
用户3138095

好的,这很不稳定,肯定不是“正确”的方法,但它似乎起作用。

我在查看输出后发现了这一点

print(tostring(myproto.fields.foo))

这似乎会输出ProtoField的每个成员的值,但是我无法找出正确的访问方式。因此,我决定解析字符串。此函数将返回' Foo',但也可以调整以返回其他字段。

function getnamefield--首先,将字段转换为字符串

--这将导致长字符串
--一堆我们不需要的信息

local fieldString = tostringfield-- fieldString看起来像:
-- ProtoField(188403):Foo  myproto.foo  base.DEC 0000000000000000 00000000(null)

--在“。”上拆分字符串
ab = fieldStringmatch“([^。] *)。 (。*)”
--在先前结果(a)的前半部分上拆分“:”字符
ab = amatch“([^。] *):(。*)”

--此时,b将等于“Foo myproto”,
--我们要去掉那个缩写“abvr”部分

--计算字符串中空格出现次数
local spaceCount = select(2,string.gsubb,“”,“”))

--声明一个计数器
local counter = 0

--声明我们要返回的名称
local constructedName =''

--按空格分隔(b)中的每个单词按顺序进行步骤
for word in bgmatch“%w +” do
    --如果我们已到达最后一个空格,请继续返回
    if counter == spaceCount-1  then
        return constructedName
    end

    --向我们的名称添加当前单词
    constructedName = constructedName .. word ..“”

    --增加计数器
    counter = counter + 1
end
end

2018-08-27 22:59:49
用户2755698
用户2755698

一种更简洁的备用方法:

local fieldString = tostring(field)
local i, j = string.find(fieldString, ": .* myproto")

print(string.sub(fieldString, i + 2, j - (1 + string.len("myproto")))

编辑:或者一种更简单的适用于 任何 协议的解决方案:

local fieldString = tostring(field)
local i, j = string.find(fieldString, ": .* ")

print(string.sub(fieldString, i + 2, j - 1))

当然,第二种方法仅在字段名称中没有空格的情况下起作用。由于这不一定总是成立,第一种方法更为健壮。以下是将第一种方法封装为应该能够被任何解剖仪使用的函数:

-- The field is the field whose name you want to print.
-- The proto is the name of the relevant protocol
function printFieldName(field, protoStr)

    local fieldString = tostring(field)
    local i, j = string.find(fieldString, ": .* " .. protoStr)

    print(string.sub(fieldString, i + 2, j - (1 + string.len(protoStr)))
end

... 在这里使用:

printFieldName(myproto.fields.foo, "myproto")
printFieldName(someproto.fields.bar, "someproto")
2018-08-28 16:05:34