如何在初始化期间自引用表

Sid*_*ode 6 lua lua-table

有没有更短的方法来做到这一点:

local thisismytable = {
    non = sequitur
}
thisismytable.whatismytable = thisismytable
Run Code Online (Sandbox Code Playgroud)

任何帮助,将不胜感激.我不想重新创建预先存在的功能.

Tom*_*get 5

没有.

如果你可以thisismytable:whatismytable()代替这两个表达式之间的区别 thisismytable.whatismytable,你可以这样做:

local thisismytable = {
    non = sequitur,
    whatismytable = function (self) return self end
}
Run Code Online (Sandbox Code Playgroud)

测试:

print(thisismytable)
print(thisismytable:whatismytable())
Run Code Online (Sandbox Code Playgroud)

更多用法:

print(thisismytable:whatismytable().non)
Run Code Online (Sandbox Code Playgroud)


Zde*_*las 5

你不能。我使用辅助函数。

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)
Run Code Online (Sandbox Code Playgroud)