Parent of "load script"?

When using the “load script” command I was expecting script to be loaded as a child of the main script. The definition for the command says “You can get this object’s properties or call its handlers as if it were a local script object”, which is true enough but it doesn’t apply to the use of the “continue” statement. When the loaded script calls continue for a handler it simply throws an error “Can’t continue …” rather than running that handler in the main script.
The problem is that the main script is not the parent of the loaded script. Is there any way to dynamically set the parent? Or somehow copy the script, add a “parent” property, and then load it?

When loading an script is indeed loaded as an script object with already an predefined parent class (which is mostly current application) unless you define it

for instance to create an perenting chain to you likings you should use something like:

on newInstance(_parent)
	script dummy
		property parent : _parent
		
		on showSomething()
			continue showSomething()
		end showSomething
	end script
end newInstance

set theObject to newInstance(me)
theObject's showSomething()
theObject's anotherHandler()

on showSomething()
	display dialog "Hello world!"
end showSomething

on anotherHandler()
	display dialog "Goodbye!"
end anotherHandler

As you can see the parenting dummy script object is an child of the main script object. Continue as missing handlers will follow the parenting chain.

Hm, thanks for that. Using the same principle I managed to work out this kinda weird solution to load scripts:

on load script theScript
	set source to do shell script "osadecompile " & quoted form of POSIX path of theScript
	set text item delimiters to return
	set source to {"on run args", "script", "property parent : item 1 of args", source, "end script", "end run"}
	return run script source as text with parameters me
end load script

When I use it with external files I store the newInstance(_parent) handler in the external file so you get something like:

set theLib to load script file theScriptFile
set theObject to theLib's newInstance(me)

It has two script objects, theLib and the script object returned by newInstance(_parent) but you don’t need to decompile and compile the script and use an do shell script. Also you can use it with run-only scripts when you ever want to distribute…

Right, problem is I’m loading script files from various sources which won’t necessarily have newInstance() in them, so I need to be able to do it dynamically from the main script. True, the decompilation won’t work for run-only scripts but I don’t think that will be a problem for me. It seems to be working well so far :slight_smile:

Thanks DJ, this was incredibly helpful. It’s also incredibly clever.