__newindex but with call custom function

Hi, I want to call function after __newindex called, but I have error “delay in metamethod”, cus I use wait() in function, I tried add coroutine to __newindex, but this not helpful. P.S: I can use bindable event, but I want better way to make this.

Example of what I do:

local Table = {}
setmetatable(Table,{
__newindex = function(self_table,index,value) -- also when I "print(Table)" index is not exist.
wait(1) -- error, cus I use delay
print("Index is:"..index)
end})
Table["test"] = "k"

If you want to make a metatable, replace __newindex with __index, as __index is the metamethod.

I just want do something with delay when table index changed

coroutine.wrap(function()
    wait(1)
    print("Index is:"..index)
end)()

You can’t yield in metamethods, at all. Why do you want something like this?

I want keep event connections in table, and set delay on __newindex call to disconnect event.

Not work, because index is nil

What is the problem here it isn’t printing the index? I copied and pasted your script working completely fine for me

?

image

I tried this:

local Table = {}
setmetatable(Table,{
	__newindex = coroutine.wrap(function(self_table,index,value) -- also when I "print(Table)" index is not exist.
		wait(1) -- error, cus I use delay
		print("Index is:"..index)
	end)()})
Table["test"] = "k"

What is the purpose of delaying by a second?

You put the coroutine inside of the newindex function

local Table = {}
setmetatable(Table, {
	__newindex = function(self_table, index, value)
		coroutine.wrap(function()
			wait(1)
			print("Index is:"..index)
		end)()
	end
})
Table["test"] = "k"
1 Like

Oh, but why I need create two functions?

Because you need a function to wrap in a coroutine

Last question, why Table index is nil after this call?
I need return something from call?

What do you mean? Table["test"] is nil when you try to print it?

Yes, or if I try print(Table).

Yes, you’re overwriting the table’s __newindex metamethod. You need to set the value of the table inside your new __newindex metamethod

rawset(Table, index, value)

I also recommend you read this:

Thanks, I read already, but I lazy to read all information.