How many times should I index a variable directly before considering making it a variable?

I wonder if there’s an easy rule for how many times I can directly index a variable before creating a new variable for it becomes a more optimal solution.

For example, when will this

if foo[item.Name] then
  foo[item.Name] = 13
else
  foo[item.Name] = false
end

Be faster than this

local name = item.Name
if foo[name] then
  foo[name] = 13
else
  foo[name] = false
end

Yes I could always run tests, but I wondering if there’s a general rule to follow.

It seems to be the same.
But you can do a benchmark using this idea:

I tend to create references for objects/properties/values that I intend to use multiple times (more than once) in order to avoid repeating myself.

Just be wary of the local variable/upvalue limits.

  • Local variables: 200 per function (same as all versions of Lua, this includes function arguments)
  • Upvalues: 200 per function (up from 60 in Lua 5.1)
  • Registers: 255 per function (same as all versions of Lua, this includes local variables and function arguments)
  • Constants: 2^23 per function (up from 2^18 in Lua 5.1)
  • Instructions: 2^23 per function (up from 2^17 in Lua 5.1, although in both cases the limit only applies to control flow)
  • Nested functions: 2^15 per function (down from 2^18 in Lua 5.1)
  • Stack depth: 20000 Lua calls per Lua thread, 200 C calls per C thread (e.g. coroutine.resume / pcall nesting is limited to 200)