tesselode
tesselode

Reputation: 101

Lua find out what table a value is in

Consider the following:

player = {}
player.shape = {x = 0, y = 0, w = 50, h = 50}

Is there a function in Lua that would tell me what table player.shape is in? I want to be able to do something like this:

shape_a = player.shape
some_function(shape_a) = player

Upvotes: 0

Views: 3842

Answers (3)

speeder
speeder

Reputation: 6296

You are probably talking about box2D or Chipmunk physics. (I am referring to the comment in Nicol Bolas reply).

Both of them have a way to do that provided, if I remember well, in Chipmunk (it is my guess about what you are using) there are a data field.

From Chipmunk manual:

cpDataPointer cpBodyGetUserData(const cpBody *body)
void cpBodySetUserData(cpBody *body, const cpDataPointer value)

User data pointer. Use this pointer to get a reference to the game object that owns this body from callbacks.

Upvotes: 0

Nicol Bolas
Nicol Bolas

Reputation: 473457

A value in Lua can be anywhere. It can be in many different places at once. Indeed, your code clearly shows it:

shape_a = player.shape

The shape table is now in two places: the global table (under the name shape_a) and the player table (under the name shape).

Values can be in local variables, which don't actually have names (not once the compiler is through with them.

What you want is generally not possible.

Upvotes: 1

catwell
catwell

Reputation: 7020

Why not just store a reference to the parent table in the shape?

player = {}
player.shape = {x = 0, y = 0, w = 50, h = 50, parent = player}

You can do that automatically with metamethods like this:

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}

Now you can access the player from the shape by calling shape.parent.

Upvotes: 8

Related Questions