6

Is there a shorter way to do this:

local thisismytable = {
    non = sequitur
}
thisismytable.whatismytable = thisismytable

Any help would be appreciated. I don't want to re-create pre-existing functionality.

Tom Blodget
  • 20,260
  • 3
  • 39
  • 72
SideCode
  • 63
  • 3

2 Answers2

5

No.

If you can stand the difference between these two expressions thisismytable:whatismytable() instead of thisismytable.whatismytable, you could do:

local thisismytable = {
    non = sequitur,
    whatismytable = function (self) return self end
}

Testing:

print(thisismytable)
print(thisismytable:whatismytable())

More usage:

print(thisismytable:whatismytable().non)
Tom Blodget
  • 20,260
  • 3
  • 39
  • 72
  • Wow, that's actually kind of genius. Thank you. – SideCode Sep 12 '15 at 15:43
  • It's a possibility, but not that genius :/ `:` just sends the accessed table as first argument to called function - it's just a wrapper around your attempt with function overhead. – Youka Sep 13 '15 at 00:39
  • 1
    @Youka I agree. I'd just do it the straightforward way like in the question. – Tom Blodget Sep 13 '15 at 01:31
  • @Youka Yeah, I decided to avoid the overhead, but still, as just kind of puzzle-solving, I thought it was pretty clever. – SideCode Sep 21 '15 at 20:31
5

You can't. I use a helper function.

local function ref(t)
  for k, v in next, t do
    if v == ref then t[k] = t end
  end
  return t
end

local root = ref{left=ref, right=ref}
assert(root.left == root)
Zdeněk Pavlas
  • 357
  • 2
  • 5