Problem unloading multiple collection

I am just recently learning lua

func = { 
  lobby_load = function: 0x029a4950,
  setting_unload = function: 0x029a4910,
  setting_load = function: 0x026c5d20,
  unload_all = function: 0x029b4940,
  auth_load = function: 0x029a4a00,
  auth_unload = function: 0x029a4990,
  lobby_unload = function: 0x029a48d0
}

global_.loaded_proxy = {
  1 = "lobby",
  2 = "setting"
}

for key,value in pairs(global_.loaded_proxy) do
  func[value .. "_unload"]()
end

but called only lobby_unload()
but should lobby_unload() and setting_unload()

why does the cycle not continue?

Hard to say why it’s not working. The code looks good. Add some print() calls or step through the code with the debugger.

yes. very strange. proxy unload correctly. if i comment caling function all works fine.

for key,value in pairs(global_.loaded_proxy) do
  --func[value .. "_unload"]()
  pprint(value)
end

show lobby and setting

function func.lobby_unload()
	msg.post("main:/go#lobby_proxy", "disable")
	msg.post("main:/go#lobby_proxy", "unload")
	helper.table_remove(global_.loaded_proxy, "lobby")
end

function func.setting_unload()
	msg.post("main:/go#setting_proxy", "disable")
	msg.post("main:/go#setting_proxy", "unload")
	helper.table_remove(global_.loaded_proxy, "setting")
end

just if not unload i get message
ERROR:GAMESYS: The collection /lobby/setting/setting.collectionc could not be loaded since it was already. Message ‘load’ sent from lobby:/go#index to main:/go#setting_proxy.
ERROR:GAMESYS: The collection /lobby/setting/setting.collectionc could not be enabled since it is already. Message ‘enable’ sent from lobby:/go#index to main:/go#setting_proxy.

Removing items from a table while you are iterating through it generally messes up the iteration. Each time you remove an element it shifts the others, so the loop will skip some elements. If you want to do that, you should use a backwards ‘for’ loop—loop from the last item to the first so you don’t interfere with the loop.

for i=#global_.loaded_proxy,1,-1 do
	local proxy_name = global_.loaded_proxy[i]
	func[proxy_name .. "_unload"]()
end

NOTE: This only works if your table is a numerical list with no holes in it!

1 Like

yes sir ))

Each time you remove an element it shifts the others, so the loop will skip some elements.

how could i forget :sweat_smile:

many thanks

p.s.

lua does not treat a variable as a new instance :stuck_out_tongue_winking_eye:

but only by reference

so you need to copy the table

function helper.table_value_index(array, value)
	for i, v in ipairs(array) do
		if v == value then
			return i
		end
	end
	return nil
end

and finally

function func.unload_all()
	if #global_.loaded_proxy ~= 0 then
		
		local proxy = helper.table_shallow_copy(global_.loaded_proxy)
		
		for key,value in pairs(proxy) do
			func[value .. "_unload"]()
		end
	end
end