私は AppleScript 参照に混乱しています... 私はほとんど AppleScript で開発したことがなく、AppleScript が参照を処理する方法に関する適切なドキュメントを見つけるのに非常に苦労しています。AppleScript のため、次のコードは失敗しますCan’t make firstValue of hash into type reference.
。
on run
foo()
end run
on foo()
set the hash to {firstValue:1, secondValue:2}
set the hashRef to a reference to the hash
return the firstValue of hashRef
end foo
しかし、次のコードは機能します-同じコードですが、run
ハンドラーではなくハンドラー内で実行していfoo
ます:
on run
set the hash to {firstValue:1, secondValue:2}
set the hashRef to a reference to the hash
return the firstValue of hashRef
end run
2 番目のコード例は機能するのに、最初のコード例は失敗するのはなぜですか? より良い質問です。誰かがこれを説明するドキュメントの方向性を教えてくれますか?
編集:フィリップの答えは私を正しい方向に向けてくれました。今、何が私を混乱させたのかがわかります。AppleScript の公式ドキュメントには、「AppleScript はすべてのパラメーターを参照渡しします。つまり、ハンドラーが set コマンドを使用して変数を作成したかのように、渡された変数がハンドラーと呼び出し元の間で共有されます」と記載されています。ただし、これは、AppleScript が各パラメータとしてAppleScript 参照オブジェクトを渡しているという意味ではありません。
以下は、私が開発した最終的な実用的なソリューションを示す、より詳細なコード例です。
on run
foo()
end run
on isRef(someValue)
try
someValue as reference
return true
on error
return false
end try
end isRef
on foo()
log "In foo()"
set the objectList to makeObjectList()
log "objectList isRef =" & isRef(objectList)
set theObject to makeObject given id:0, name:"Test"
addObjectToObjectList(theObject, objectList)
log "foo(): object name =" & name of theObject
log item 1 of allItems of objectList
log item 1 of goodItems of objectList
set the name of item 1 of allItems of objectList to "Test3"
log item 1 of allItems of objectList
log item 1 of goodItems of objectList
end foo
on makeObjectList()
set the hash to {allItems:{}, goodItems:{}, badItems:{}}
return the hash
end makeObjectList
on makeObject given name:theName, id:theId
set theObject to {name:theName, id:theId}
return theObject
end makeObject
on addObjectToObjectList(object, objectList)
log "In addObjectToObjectList"
log "object isRef =" & isRef(object)
copy object to the end of allItems of the objectList
set objectRef to a reference to the last item in allItems of the objectList
set name of objectRef to "Test2"
log "object name =" & name of object
log "objectRef isRef =" & isRef(objectRef)
log "objectRef name =" & name of (contents of objectRef)
copy objectRef to the end of goodItems of the objectList
end addObjectToObjectList
その出力は次のとおりです。
(*foo()*で) (*objectList isRef =false*) (*addObjectToObjectList* 内) (*オブジェクト isRef =false*) (*オブジェクト名 =Test*) (*objectRef isRef =true*) (*objectRef 名 =Test2*) (*foo(): オブジェクト名 =Test*) (*名前:Test2、id:0*) (*名前:Test2、id:0*) (*名前:Test3、id:0*) (*名前:Test3、id:0*)
要点は、ハンドラー内でローカル変数を参照することはできませんが、レコードの一部を参照することはできますが、それらの参照がそのレコードに保存されている限り、これが私が求めていた機能です。
この質問をここまで読んだ人はいないと思います:-)