Search code examples
lualua-table

Can I know from inside a subtable to which parent's key belongs directly while created?


It just passed through my mind and now I'm curious, so... Let's say I have this:

RL_Test.src = {}
RL_Test.src[1] = {["d"] = {["ID"] = 1, ["name"] = "NAME1"}}
RL_Test.src[2] = {["d"] = {["ID"] = 2, ["name"] = "NAME2"}}

Do you think there could be a way to set the value of the subtable's entries "ID" automatically accordingly to the key numbers of the table they belong directly? I mean, without having to parse/loop through the parent table or anything like that. I don't see the way and surely is for a good reason... but just wondering if it could be achieved by mean of one of those Lua tricks or something I'm missing. Thanks.


Solution

  • If you are filling RL_Test.src with consequtive integer indices, you can just get its length:

    RL_Test.src = {}
    RL_Test.src[#RL_Test.src + 1] = {["d"] = {["ID"] = #RL_Test.src + 1, ["name"] = "NAME1"}}
    RL_Test.src[#RL_Test.src + 1] = {["d"] = {["ID"] = #RL_Test.src + 1, ["name"] = "NAME2"}}