I’m new to Lua and I want to create a table [doh] which would store values like:
parent.child[1].value = "whaterver"
parent.child[2].value = "blah"
however, most often there’s only one child, so it would be easier to access the value like this:
parent.child.value
To make things simpler, I would like to store my values, in a way, that
parent.child[1].value == parent.child.value
But to do this I would have to store this value twice in the memory.
Is there any way I could do it, so that:
parent.child.value points to parent.child[1].value
without storing the value twice in the memory?
Additional question is, how to check how much memory does a table take?
First, all types (except booleans, numbers and light userdata) are references – if
tis a table and you dot2 = t, then bothtandt2are references to the same table in memory.Second thing – string are interned in Lua. That means that all equal strings, like
"abc"and the result of"ab".."c"are actually a single string. Lua also stores only references to strings. So you should not worry about memory – there is only a single instance of the string at a time.You can safely do
parent.child.value = parent.child[1].value, you will only use a memory for one slot in a table (a few bytes), no string will be copied, only referenced.