Is there something like signposts in Lua?

I am new to Lua and I want to create a [doh] table that will store values โ€‹โ€‹such as:

parent.child[1].value = "whaterver"
parent.child[2].value = "blah"

however, most often there is only one child, so it would be easier to access a value like this:

parent.child.value

To make things easier, I would like to keep my meanings in such a way that

parent.child[1].value == parent.child.value

But for this I would have to store this value twice in memory. Can I do this to:

parent.child.value points to parent.child[1].value

without storing the value twice in memory?

Additional question: how to check how much memory a table occupies?

+5
source share
4 answers

but the value will be saved as a row, so a row that should be referenced in both places, not the table.

-, ( , ) - t - , t2 = t, t, t2 .

- Lua. , , "abc" "ab".."c", . Lua . - .

parent.child.value = parent.child[1].value, ( ), , .

+10

Lua ( ) , . ( )

+3

:

parent={
    child={
        {value="whatever"},
        {value="blah"}
    }
}
setmetatable(parent.child,{__index=parent.child[1]})

(, "" ), , __index ( ).

, folows:

print(parent.child.value) -- prints whatever
parent.child[1]=nil --remove first child
print(parent.child.value) -- still prints whatever!

, metatable , . : A) B) __index .

-- A)
setmetatable(parent.child, setmetatable(
    {__index=parent.child[1]} -- metatable for the child table
    {__mode='v'}-- metatable for the metatable, making it have weak keys
    )
)
parent.child[1]=nil
print(parent.child.value) --returns nil
parent.child[1]={value='foo'} 
print(parent.child.value) -- prints nil, the metatable references to a non-existant table.
-- hence solution B)

setmetatable(parent.child, {__index=function(t,k) return parent.child[1][k]})
print(parent.child.value) -- 'whatever'
parent.child[1]=nil
print(parent.child.value) -- nil
parent.child[1]={value='foobar'
print(parent.child.value) -- foobar, now it will always refer to the table at child[1], even when it changes.

, Lua, 13 17 ( ). - Lua-Users MetaMethods .

+3

C, parent.child parent.child[0] - . , C , .

0

All Articles