Page 1 of 1

Metamethod for reading any item

Posted: Sat Jan 05, 2019 2:09 am
by lazi
I am sorry, but always trying to do things that Hollywood not intended to do. :)

The metamethods are really great possibilities. But... there is no metamethod like __index for every read access of a table.
I would like to replace a table usage in a large script, and instead of change every line that access the table I thought that
temporarily change the access method of the table would be a good idea.

Re: Metamethod for reading any item

Posted: Sat Jan 05, 2019 4:01 am
by p-OS
Well, __index and __newindex only work for non-existing entries in a table.
You want them to work for every access (also for existing table entries), Right ?

There is a workaround:

Put a table around your existing table, with index and newindex defined.

Example:

you have:

mytab={1,2,3}

make instead:

mytab={
oldmytab={1,2,3}
}

now define a metatable for (new) mytab, that defines __index and __newindex.

As (new) mytab has no entries, every access to a table member actually is considered as access to non-existent entry.

exception: access to mytab(oldmytab)

in __index metamethod you should do sth. like that:
check if there is an entry in oldmytab with the requested index and return its value

in __newindex metamethod, you should do sth. like that:
check if there is an entry in oldmytab with the requested index.
if yes, update its value.
of no, add a new entry to oldmytab with the requested index and given value.

-->
mytab("bla")=3 would actually set (new or update) mytab.oldmytab("bla")
result=mytab("bla") would actually read mytab.oldmytab("bla")

Re: Metamethod for reading any item

Posted: Sat Jan 05, 2019 6:44 pm
by lazi
Thanks p-OS for the suggestion!
I thought something similar myself too, but suggested a more simpler solution scriptwise.

Re: Metamethod for reading any item

Posted: Sun Jan 06, 2019 3:19 am
by p-OS
Hi,

if you have an even simpler solution (working with the current Hollywood version), please share your ideas !

My suggestion was the simpler version of what i actually implemented for my purposes:

Code: Select all

mytab={
         x=3,
         y=7,
         z=9
      }

-->

mytab={
        oldmytab={
                  {"x", 3 },
                  {"y", 7 },
                  {"z" , 9}
                }
      }       
My private solution results in this behaviour:

mytab("bla")=3 would actually set (new or update) mytab.oldmytab({"bla",3})
result=mytab("bla") would actually read the mytab.oldmytab({"bla"})

The index given when accessing mytab table becomes a private field in a table within oldmytab.
oldmytab itself has a (implicit) numeric index starting with 0