Skip to content

Instantly share code, notes, and snippets.

@exerro
Created January 27, 2023 20:20
Show Gist options
  • Save exerro/64ddf7f7a21cb69d3c9fd354d6c6e5e2 to your computer and use it in GitHub Desktop.
Save exerro/64ddf7f7a21cb69d3c9fd354d6c6e5e2 to your computer and use it in GitHub Desktop.
gotcha
local function safeIndex(t, ...)
for _,v in ipairs({...}) do
t = t[v]
if not t then return nil end
end
return t
end
local function safeIndex2(t, ...)
local it = { ... }
for i = 1, #it do
t = t[it[i]]
if not t then return nil end
end
return t
end
local function timeit(name, f)
local time = ccemux and function() return ccemux.nanoTime() / 1000000000 end or os.clock
local example = { a = { b = { c = 42 } } }
local start = time()
assert(f(example, 'a', 'b', 'c') == 42)
for i = 1, 1000000 do
f(example, 'a', 'b', 'c')
end
print(string.format("%s took %.1fs", name, time() - start))
end
timeit('safeIndex', safeIndex)
timeit('safeIndex2', safeIndex2)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment