lua - Lua中元表访问时的时间复杂度

标签 lua lua-table metatable

local cls = {base = "base"}
local ins = {}
cls.__index = cls
setmetatable(ins, cls)

访问 ins.base 的时间复杂度是多少?

最佳答案

官方 Lua 实现的时间复杂度预计为 O(1)

__index 的代码大致相当于此 Lua 代码,摘自手册:

 function gettable_event (table, key)
   local h
   if type(table) == "table" then
     local v = rawget(table, key)
     if v ~= nil then return v end
     h = metatable(table).__index
     if h == nil then return nil end
   else
     h = metatable(table).__index
     if h == nil then
       error(···)
     end
   end
   if type(h) == "function" then
     return (h(table, key))     -- call the handler
   else return h[key]           -- or repeat operation on it
   end
 end

__index 查找本身没有循环,并且由于 Lua 表由哈希表支持,因此表查找通常是恒定时间操作。

关于lua - Lua中元表访问时的时间复杂度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23259396/

相关文章:

lua - Corona SDK 上的 Admob Interstitial 仅显示一次

for-loop - Lua for循环减少我?奇怪的行为

c++ - 将嵌套表从 Lua 传递到 C

lua - 如何理解 Lua 中的元表?

lua - Lua 自定义类中的 __tostring

lua - 加载 Lua 文件并捕获任何语法错误

lua - 如何使用 Corona SDK 在 Lua 中自动调整 View 大小?

c++ - 如何从 Lua 函数中获取多个返回表?

c++ - 使用 SWIG 包装 C++ 函数以获取字符串的 Lua 表

lua - 是否可以像在 Lua 中 rawget/set 绕过 __index/__newindex 那样绕过 __tostring?