The error happens when you try connecting to a multiplayer game in progress - I've only tested locally with joining the game as a second player, but I would assume it's going to happen when trying to connect to a headless server even as the first player to join due to how the client/server code works in Factorio.
The underlying issue causing the bug is that for each player and/or the server, you register and then remove the on_tick handler:
- Player 1 / Server "joins" the game: control.lua runs and registers the on_tick handler, which runs itself and then removes itself
- Player 2 joins the game: control.lua runs on their machine and registers the on_tick handler which has already been removed from the server machine, thus causing Factorio to disconnect the player.
The easiest way to fix this is to just not remove the on_tick handler - since you already have the "if not global.scanned_map" line in there, it would be safe to leave it in there, and should be fairly performance friendly (a single if statement is not going to cause much issue).
If you really -really- are concerned about performance, you could also move the entire scan code off to a separate function that you call from your event loop and simply set the function after it's run once into a function that doesn't actually do anything - Lua functions are variables, so they can be changed at runtime; thus when you want to stop doing something you can always just say "nameOfTheFunction = function() end" and it turns the function into a no-op.
I've created this gist to show how that could be done (with a diff between the initial version and the updated version) - https://gist.github.com/legendblade/2da44f5ec652f83780fc384b28961bfb/revisions#diff-2f29ee9c98c28d035046fb40285456da
Hope that helps.