Question

I have made a lua console on the love2d engine which is irrelevant. I am trying to upgrade the metatables to be able to effect more things (the pairs function, change the metatable on another table instead of the targeted one etc.) and one of the addons I am making is a __changeindex event for when you modify an existing index.

In order to do this I have to give the user a dummy table that holds no values and when they try to add something check if that is already defined in the real table, if it is then call __changeindex, if it is not then call __newindex. This works perfectly however this causes many other Lua table functions to stop working (for loops/getmetatable/setmetatable). I have made workarounds for most of those issues and they work fine but I cannot get the #t operator working, I would like to be able to say

t1={1,2,3}
t2=setmetatable({},{__getn=function(self) return #t1 end})

and then #t2 should really return #t1. Is there any way for me to do this?

my existing code for this can be found here

EDIT: this is my first post so I apologise if I have not followed the posting rules perfectly, I tried :) also if anyone has a way to make the fake and real tables garbage collect I would really appreciate it

Was it helpful?

Solution

There no __getn metamethod. Try __len instead. This works only on Lua 5.2

You cannot overload the # operator for tables in Lua 5.1

You could use userdata to create a proxy object:

t = newproxy(true)
getmetatable(t).__len = function()
    return 5
end

print(#t) --> 5

Note however, that the newproxy function is undocumented.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top