user3713179
user3713179

Reputation: 361

Retrieve table from key

Is there a way to retrieve the table to which belongs the key from the key itself? For exampe

tbl { Italy = "Roma" }

Can I go back to tbl from Italy?

Upvotes: 1

Views: 76

Answers (3)

Tom Blodget
Tom Blodget

Reputation: 20772

A key is any value other than nil. In this case, you have a string value: "Italy". No value has the general concept of "parent" or "owner". Nonetheless, you can create structures to which you apply that concept if you need to.

local capitals = {}
capitals.Italy = { capital = "Roma", collection = capitals }
capitals["Czech Republic"] = { capital = "Prague", collection = capitals }

local playwrights = {}
playwrights["William Shakespeare"] = { born = 1564, died = 1616, collection = playwrights }


local fact = capitals.Italy
print(fact.collection == capitals)

Upvotes: 0

Oliver
Oliver

Reputation: 29453

You can't do what you want to do for attributes (table fields) but you can do it with methods:

function tbl.getItaly(self)
     return self.Italy
end

Then tbl:getItaly() returns the Italy of tbl; in methods, self is given implicitly by Lua interpreter and represents the table that contains the called method. Note that you need to use colon not dot syntax.

Upvotes: 0

Paul Kulchenko
Paul Kulchenko

Reputation: 26744

No, but you can save the reference to the table itself in the element:

tbl = {}
tbl.Italy = {"Roma", tbl}
print(tbl == tbl.Italy[2])

prints true.

Upvotes: 2

Related Questions