Using variables

Sorry about the vague subject… i didn’t know how to better describe my issue

I would like to use a variable like this:

set x to artist

tell application "iTunes"
	get x of current track
end tell

where x can be for example artist or name

But this doesn’t work. Is there any workaround?

thanks in advance!

Hi illi,

this is only possible with second level evaluation,
using the property as a string

set x to "artist"
set y to "name"
getData(x)
getData(y)

on getData(p)
	tell application "iTunes"
		try
			run script "get " & p & " of current track"
		on error
			return false
		end try
	end tell
end getData

This sort of thing is trivial to do in languages that support introspection, e.g. in Ruby:

[code]#!/usr/bin/env ruby

require “appscript” # (http://rb-appscript.rubforge.org)
include Appscript

x = “artist”

p app(“iTunes”).current_track.send(x).get

→ “Perry Como With Mitchell Ayres And His Orchestra”[/code]

In AppleScript, the clean solution is to define a bunch of interchangeable script objects, each of which is responsible for getting one of the properties you need in response to a common command (getProp(trackRef) in the example code below). You can then assign those objects to variables, pass them around your program, etc. as normal, and any time you want to get the value of a track property, just send a ‘getProp’ command with a reference to the desired track:

using terms from application "iTunes"

    script GetName
        on getProp(trackRef)
            get name of trackRef
        end getProp
    end script
    
    script GetArtist
        on getProp(trackRef)
            get artist of trackRef
        end getProp
    end script
    
    script GetAlbum
        on getProp(trackRef)
            get album of trackRef
        end getProp
    end script

    -- etc.

end using terms from

tell application "iTunes" to set myTrack to current track

set x to GetName
x's getProp(myTrack)
--> "Papa Loves Mambo"

set x to GetArtist
x's getProp(myTrack)
--> "Perry Como With Mitchell Ayres And His Orchestra"

It’s a rather verbose solution as you can see, but it’s fast and reliable. The dirty alternative is to hack it using code generation a-la StefanK’s suggestion, although the run script command is relatively slow and code generation can easily introduce bugs/security holes if you’re not careful.

HTH