Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
1

Is there any Lua metamethod that gets called when a table's value is referenced?

Asked by
movsb 242 Moderation Voter
7 years ago

Basically I am wondering if there is any metamethod, or standard (or un-standard / outside of the box) way to tell when a table's value is being referenced.

For example the metamethod "__newindex", is called every time you create a new index inside of the metatable, so if I did this to a metatable with the metamethod __newindex it would call the metamethod:

myMetaTable.MyNewIndex = 123;

But what if you were only referencing, or getting the value inside of a metatable like these two examples: (assuming that "oldIndex" is not a nil value inside of MyMetaTable)

local new_value = MyMetaTable.OldIndex;

and

print(MyMetaTable.OldIndex);

It is in these particular cases that I am wondering if there is a metamethod or some method to tell when a table's value(s) are being referenced. To go more in-depth, I am working with Lua Object Oriented Programming, and there is a certain property that I need to keep inside all instances of a class called ID, which is used to find that instance's private property data, which is stored in a somewhat 'hidden' scope. What I would essentially LIKE to do is not allow users to reference the ID property, for example say that there WAS a metamethod that would be called each time a value of a table was referenced, and the value the method returned would be returned instead of the actual value of the property. For example say that a metamethod called '__ref' existed for simplicity:

meta = {__index = {ID = 0}};
meta.__ref = function(k, v)
    if k == "ID" then
        return nil;
    end
    return v;
end

In theory this would essentially hide the 'ID' property, but I am not sure if a metamethod like this exists, nor do I know of any methods to do this. If anyone can help I would appreciate it.

1
I suggest to use a function as __index. There is no __ref (or similar) meta method. To my knoledge, the functionality neither exists in Roblox or standard lua. Meta method pages: http://wiki.roblox.com/index.php?title=Metamethods http://lua-users.org/wiki/MetatableEvents Epidemiology 116 — 7y
0
Thank you, I did not realize that I could use the __index metamethod that way! movsb 242 — 7y

Answer this question