优化的Lua表搜索

问题描述

我有一个LUA表:

local tableDatabase = {
  name = uniqueName,class = val_one_to_eight,--not unique
  value = mostly_but_not_guaranteed_unique_int}

此表可以按上述任何一种进行排序,并且可能包含非常大的数据集。

现在要插入,我只是遍历表对,直到找到:

 insertedvalue.uniqueName > tableDatabase.uniqueName
 --(or comparing the other parms instead if they are the selected sort order.)

我需要此功能才能超快速地工作。是否有人建议使用搜索算法在表中查找要插入的索引,或者我可以使用某种方法在lua表上对其进行优化以提高插入速度?

解决方法

我知道,对于严格有序的结构,您可以使用二进制搜索或类似的算法。 Lua用户provides随时可以使用该功能。

,

为什么不在name上创建索引?如果速度不够快,则可以降低__index的通用性,即对name上的唯一索引进行硬编码。

-- Returns a table. ... is a list of fields,for which unique indices should be created:
function indexedTable (...)
    local t = {
        __indices = {},__insert = function (self,value)   -- instead of table.insert.
            self [#self + 1] = value    -- implicily calls metamethod __newindex.
        end     
    }
    -- Initialise indices:
    for _,index in ipairs {...} do
        t.__indices [index] = {}
    end
    setmetatable (t,{
        -- Allow t [{name = 'unique'}]:
        __index = function (t,key)
            if type (key) == 'table' then
                for index_key,index_value in pairs (key) do
                    local value = t.__indices [index_key] [index_value]
                    if value then
                        return value
                    end
                end
            else
                return rawget (t,key)
            end
        end,-- Updates all indices on t [k] = v,but doesn't work on table.insert,so use t:__insert"
        __newindex = function (t,key,value)
            -- insert uniqueness constraint here,if you want.
            for index_key,index in pairs (t.__indices) do
                index [value [index_key]] = value
            end
            rawset (t,value)
        end
    })
    return t
end

-- Test:

local tableDatabase = indexedTable ('name')

-- Not table.insert,as it is not customizable via metamethods:
tableDatabase:__insert {
    name    = 'unique1',class   = 1,value   = 'somewhat unique'
}

tableDatabase:__insert {
    name    = 'unique2',class   = 2,value   = 'somewhat unique'
}

tableDatabase:__insert {
    name    = 'unique3',value   = 'somewhat unique but not absolutely'
}

local unique2 = tableDatabase [{name = 'unique2'}]  -- index search.
print (unique2.name,unique2.class,unique2.value)