Trying to build a dissector in lua where in the ProtoField for one of the values, I map it to a table so that when passed some uint it can get said string from the list of outputs. The current issue is that I have some indexes of 1, 2, and 3, but I also need a range of numbers that correspond to one output string, and its too many to hardcode it all in. I thought about just adding some check that will add said index whenever it doesn't exist, but that would result in alot of wasted time and wanted to ensure there wasn't a better way.
Tried mapping it to a function and setting a default value with a metatable.
Generically, a table can contain tables as indices. These tables could each be used to represent a range of indices.
A cursory example (note that overlapping ranges are not stable):
local range_mt = {}
range_mt.__index = range_mt
function range_mt:contains(value)
return self.lower <= value and value <= self.upper
end
local function range(lower, upper)
return setmetatable({
lower = lower,
upper = upper
}, range_mt)
end
local map = setmetatable({
[1] = 'hello',
[2] = 'world',
[3] = 'goodbye',
ranges = {
[range(10, 20)] = 'foo',
[range(51, 99)] = 'bar'
}
}, {
__index = function (self, value)
for r, str in pairs(self.ranges) do
if r:contains(value) then
return str
end
end
return "DEFAULT"
end
})
for _, value in ipairs { 9, 6, 1, 2, 16, 4, 15, 66, 51, 3, 94 } do
print(value, '->', map[value])
end
9 -> DEFAULT
6 -> DEFAULT
1 -> hello
2 -> world
16 -> foo
4 -> DEFAULT
15 -> foo
66 -> bar
51 -> bar
3 -> goodbye
94 -> bar