例:
player = {}
player.shape = {x = 0, y = 0, w = 50, h = 50}
Run Code Online (Sandbox Code Playgroud)
Lua中是否有一个函数可以告诉我表player.shape所在的位置,所以我可以执行以下操作:
shape_a = player.shape
some_function(shape_a) = player
Run Code Online (Sandbox Code Playgroud)
为什么不只在形状中存储对父表的引用?
player = {}
player.shape = {x = 0, y = 0, w = 50, h = 50, parent = player}
Run Code Online (Sandbox Code Playgroud)
您可以使用以下元方法自动执行此操作:
local new_player = function()
return setmetatable(
{},
{
__newindex = function(t,k,v)
if k == "shape" then v.parent = t end
rawset(t,k,v)
end,
}
)
end
player = new_player()
player.shape = {x = 0, y = 0, w = 50, h = 50}
Run Code Online (Sandbox Code Playgroud)
现在,您可以通过调用从形状访问播放器shape.parent。