4
votes

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

1
There no __getn metamethod. Try __len instead. This works only on Lua 5.2moteus
love2d uses lua 5.1 unfortunitely. I am attempting to create the __getn functionality. If you look at the code I posted I have added functionality for __next,__getn(only the table.getn version),__maxn,__changeindex,__setmetatable and am going to be adding moreKaoSDlanor
You can not overload # operator for table in Lua 5.1. You could use userdata to create proxy object. t = newproxy(true) getmetatable(t).__len = function() return 5 end print(#t)moteus
I had not heard of the newproxy function but it looks fascinating. Thank you for the assistanceKaoSDlanor
@moteus, you could move your comment to an answer.lhf

1 Answers

2
votes

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.