Change # operator to lua

I made the lua console on the love2d engine, which doesn't matter. I am trying to update metatables to be able to do more things (function pairs, change the metatet on another table instead of the target, etc.), and one of the add-ons that I create is the event __changeindexwhen you change an existing index.

To do this, I must provide the user with a dummy table that does not contain values, and when they try to add something, check if it is already defined in the real table, if it then calls __changeindex, if it is not called __newindex. This works great, but it causes many other Lua table functions to stop working (for / getmetatable / setmetatable loops). I made workarounds for most of these problems, and they work fine, but I can't get the #t operator to work, I would say

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

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

my existing code for this can be found here

EDIT: this is my first post, so I apologize, if I didn’t follow the publishing rules, I tried :) also, if anyone has a way to make fake and real garbage collection, I would really appreciate

+4
source share
1 answer

There are no __getnmetamethods. Try it instead __len. This only works on Lua 5.2

You cannot overload the statement #for tables in Lua 5.1

You can use userdata to create a proxy object:

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

print(#t) --> 5

Please note that the function is newproxy undocumented .

+2
source

Source: https://habr.com/ru/post/1526320/


All Articles