Pass an object to timer callback to delete it later

for i = 1,100 do
    local object = factory.create("#factory")
    timer.delay(math.random(1,3), false, function() go.delete(object) end)
end

How can I save an instance of the created object so I can delete it after a moment?

ERROR:SCRIPT: /mob/ai/ai_callbacks.lua:60: Instance (null) not found
stack traceback:
	[C]: in function 'delete'
	/mob/ai/ai_callbacks.lua:60: in function </mob/ai/ai_callbacks.lua:60>

Should I create a table containing all the created objects or is there a way to pass the exact instance that is created in the current iteration to the timer callback?

Would this work?

for i = 1,100 do
    local object = factory.create("#factory")
    timer.delay(math.random(1,3), false, function(object) go.delete(object) end)
end

The passed object is… Script?

timer.delay(math.random(1,3), false, function(object) pprint("DROP", object) go.delete(object) end)

Output:

DEBUG:SCRIPT: DROP,
Script: 0x01f1ee212f80
ERROR:SCRIPT: /mob/ai/ai_callbacks.lua:60: bad argument #1 to 'delete' (url expected, got userdata)
stack traceback:
	[C]: in function 'delete'
	/mob/ai/ai_callbacks.lua:60: in function </mob/ai/ai_callbacks.lua:60>

I think GO’s created by factories are always of the type “userdata”.

Strange, you’re code looks good I think… Hmm

Check the docs. The engine calls the callback with specific arguments, the first one being self (which prints out as “Script: 0x01f1ee212f80”). You need to remove 'object' from the anonymous function arguments. That’s actually self, and when you write 'object' there it overshadows the local variable (also 'object') that you just made.

local url_to_delete = msg.url("thingy")
timer.delay(0.5, false, function(self) go.delete(url_to_delete) end)

[Edit] …apparently I didn’t read your first post…It does seem like that should work. Try checking the ‘object’ directly with go.get_position or something?

[Edit 2] Your original code works just fine for me when I copy-paste it into my project. Are the objects somehow getting deleted by some other script before the timer ends?

4 Likes