0

I have a table t which is totally dynamic: it is nested, and number of levels is unknown in advance. I wish to be able to set (get is easy to do) some value at some level, using a kind of path. The path would be an array (this doesn't have to be, just an idea, but seems to make sense to me)

Here is a kind of code, which obviously doesn't work (it will always return 3), but gives an idea of what I need:

t={a={b={c=3}}}
path={"a","b","c"}
r=setmetatable(t,
for _,i in pairs(path) do
   r=r[i] 
end
r=1

print(t["a"]["b"]["c"])

I thought of using __index, __newindex and metatable, but I still struggle to use those, and all my experiments failed Otherwise, getting the address of the table, rather than its value would be the solution, but I don't know how to do that...

3
  • 2
    Close, instead of processing all indices, only traverse the first n-1, and use the last index to set r[path[#path]] = value. I would make a utility function instead of using metatables. Commented Jan 18, 2024 at 18:24
  • 2
    Does this answer your question? Writing to Dynamic Multidimensional table via path Commented Jan 19, 2024 at 7:41
  • It seems that it does. Many thanks for that (I don't understand all of it, but copy paste should do it!!!) Commented Jan 19, 2024 at 19:24

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.