最优化的方式从表中获取价值

时间:2018-01-25 17:25:52

标签: lua lua-table

我需要检查第一个值是> ='来自'第二个值是< ='到'如果为真,那么我的函数重新编号。它正在运作,但我不知道这是否是获得价值的最佳和最优化的方式(表中的数字)。

local table = {
    {from = -1, to = 12483, number = 0},
    {from = 12484, to = 31211, number = 1},
    {from = 31212, to = 53057, number = 2},
    {from = 53058, to = 90200, number = 3},
    {from = 90201, to = 153341, number = 4},
    {from = 153342, to = 443162, number = 5},
    {from = 443163, to = 753380, number = 6},
    {from = 753381, to = 1280747, number = 7},
    {from = 1280748, to = 2689570, number = 8},
    {from = 2689571, to = 6723927, number = 9},
    {from = 6723928, to = 6723928, number = 10}
}

local exampleFromValue = 31244
local exampleToValue = 42057

local function getNumber()
    local number = 0
    for k, v in pairs(table) do
        if (v.from and exampleFromValue >= v.from) and (v.to and exampleToValue <= v.to) then
            number = v.number
            break
        end
    end 

    return number
end

print(getNumber())

1 个答案:

答案 0 :(得分:1)

使用这么少的数据,这样的功能似乎不是一个性能问题。但是,您可以稍微压缩数据:

local t = {
  12484, 31212, 53058, 90201, 153342, 443163, 753381, 1280748, 2689571, 6723928
}

local exampleFromValue = 31244
local exampleToValue = 42057

local function getNumber()
  local last = -1
  for i, v in ipairs(t) do
    if exampleFromValue >= last and exampleToValue < v then
      return i - 1
    end
    last = v
  end
  return 0
end