Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
0

How do I remove functions in tables?

Asked by
lucas4114 607 Moderation Voter
7 years ago
Edited 7 years ago

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

0
Have you tried table.remove pluginfactory 463 — 7y
0
Stopping a thread is totally different from removing a function from a table. table.remove has nothing to do with this. BlueTaslem 18071 — 7y

1 answer

Log in to vote
3
Answered by
BlueTaslem 18071 Moderation Voter Administrator Community Moderator Super Administrator
7 years ago
Edited 7 years ago

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")
Ad

Answer this question