Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
✓ ANSWER ACCEPTED

How do I remove functions in tables?

So I'm trying to learn a bit of object oriented programming and I couldn't find out how to do this: if I have a function in a table how can I stop it or remove it?

I tried doing this at first:

local a = {
	b = function() 
			while wait(0.1) do
				print('test') 
			end 
		end
}

a:b()

wait(2)

a.b = nil

but I found out that it wasn't working because it was stuck at the loop, so I did this:

local a = {
	b = function() 
			while wait(0.1) do
				print('test') 
			end 
		end
}

coroutine.resume(coroutine.create(function()
	a:b()
end))

wait(2)

a.b = nil

but this didn't work too, so I have no idea what to do to remove or stop the function a.b

2 comments

0

Have you tried table.remove

0

Stopping a thread is totally different from removing a function from a table. table.remove has nothing to do with this.

1 answer

✓ Accepted answer

If you want to start work in the background, use spawn not coroutine:

spawn(function()
	a:b()
end)

Removing a property

Setting a.b = nil modifies a. It doesn't somehow cause the loop inside some function to stop.

Of course, doing that couldn't, because you can have multiple objects with the same function as a member:

local a = {f = function() end}
local b = {f = a.f}

a.f = nil
print(b.f) --> function: 0x165a720

Modifying a shouldn't somehow kill a loop on b:f().

Stopping a thread

You cannot force another "thread" to stop. Doing so is unsafe because the thread could be in the middle of some task you shouldn't interrupt -- if you interrupt it at that time, the world could be left in pieces.

Threads must voluntarily stop themselves.

Your thread has a while loop. Presumably, it shouldn't go forever if you want to stop it:

local obj = {
	method = function(self)
		while not self.stop do
			print("test")
			wait(0.1)
		end
	end
}

spawn(function()
	obj:method()
end)

wait(2)

obj.stop = true
print("stopped")

Of course in this case, there's no reason to use a thread at all, since nothing is going on in the mean time:

local stop = tick() + 2
while tick() < stop do
	print("test")
	wait(0.1)
end
print("stopped")

This discussion is preserved as it was. New answers, comments, and votes are closed.