[SOLVED] Checking collection exists before proxy loading

Hi. Having worked through the ‘what next?’ exercises at the end of the ColorSlide tutorial, I’m wondering how other people would have approached item 4: fix the case where the player completes the last level and there is no “next” one? Or rather, what’s a better way of doing what I came up with?



starting code: GitHub - defold/tutorial-colorslide

My solution, not wanting to hard code the maximum level:

level.gui_script

function init(self)
	-- get current level number
	self.whoami = tostring(msg.url())
	self.whoami = tonumber((string.match(self.whoami, "%d+")))
	-- check for the presence of a next level
	msg.post("default:/loader#loader", "check_next_level", { query_level = self.whoami + 1 })
...

loader.script

function on_message(self, message_id, message, sender)
	...
	elseif message_id == hash("check_next_level") then
		local next_proxy = "#proxy_level_" .. message.query_level
-->>								----								<<--
		local next_proxy_error = collectionproxy.missing_resources(next_proxy)
		if next_proxy_error[0] == nil then
			msg.post(sender, "confirm_next_level", { is_next_level = true })
		end
	end

back to level.gui_script

function on_message(self, message_id, message, sender)
	...
	elseif message_id == hash("confirm_next_level") then
		-- update end-of-level behaviour based on next level query
		...

This works well from the user’s perspective, though I do get a console error about the collection N+1 not existing whenever the last level is loaded:

The component could not be found: 'default:/loader#proxy_level_5

Before that I tried a custom sys.set_error_handler around where -->> — <<-- is, but ran into the problem of losing track of what level instance posted the original “check_next_level” message.

(I realise it’s a bit pointless not wanting to hard code the maximum level number when the collection proxies themselves have already been created statically, so I’m guessing I might have constructed some sort of table I could’ve used if I’d gone back and cloned them in dynamically)

You could use Lua’s pcall to handle errors, and check if your msg.post failed.

1 Like

Thanks Mathias, that’s a much simpler way (and closer to what I was attempting with sys.set_error_handler). Lua 5.1 Reference Manual

I’ll mark this as solved, but anyone else feel free to share what you did for ColorSlide task 4.

PS/ it’d be nice if there were a way of tagging forum posts like this with a tutorial name, without breaking them out of the Question category. But I suppose just searching the name works well enough.

1 Like