How to self-reference table during initialization
Asked Answered
T

2

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.

Try answered 12/9, 2015 at 14:0 Comment(0)
Q
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)
Quadrireme answered 12/9, 2015 at 14:21 Comment(4)
Wow, that's actually kind of genius. Thank you.Try
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.Ingrained
@Ingrained I agree. I'd just do it the straightforward way like in the question.Quadrireme
@Ingrained Yeah, I decided to avoid the overhead, but still, as just kind of puzzle-solving, I thought it was pretty clever.Try
M
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)
Madalena answered 12/9, 2015 at 16:53 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.