2006-04-14

함수 (handler)

다른 많은 프로그래밍 언어처럼, 애플스크립트 역시 handler라는 함수 형태를 지원합니다. 적절한 우리 말로는 그냥 핸들러라고 해야할지, 함수라고 해야할지는 잘 모르겠습니다.
handler는
on [handler name]()
return [return value]
end [handler name]
의 형태를 갖습니다. ()안에는 적당한 매개변수가 들어갑니다. 처리 결과는 return 으로 반환합니다. handler를 실행할 때에는 my를 이용합니다. 구구한 설명보다 예제를 보는 것이 훨씬 도움이 될 것 같습니다.
-- 원의 넓이 구하기
set radius to 3
set theAreaOfCircle to getAreaWith(radius)

on getAreaWith(radius)
return (radius * radius * pi)
end getAreaWith
-- 숫자의 자릿수 맞추기(adding leading zeros)
display dialog "4자리 숫자로 만듭니다. 10000보다 작은 아무 숫자나 넣으세요." default answer ""
set theNumber to my addZerosTo(text returned of the result)

on addZerosTo(theValue)
set theSize to the count of characters of theValue
if theSize is 1 then
return ("000" & theValue) as string
else if theSize is 2 then
return ("00" & theValue) as string
else if theSize is 3 then
return ("0" & theValue) as string
else if theSize is 4 then
return theValue
else
display dialog "너무 큰 숫자입니다."
end if
end addZerosTo

다른 프로그래밍 언어라면 바로 위의 예제는 컴파일이 불가능할 것입니다. 마지막 if에서는 return이 없기 때문입니다. 이런 유연함 혹은 융통성이 애플스크립트의 장점이자 단점인 것 같습니다.
handler를 이용하면 훨씬 더 이해하기 편한 스크립트를 만들 수 있습니다. 길이도 짧아지고, 덜 복잡해보일 수 있습니다.


변수의 범위에 대해서 따로 쓸 기회가 있을지는 잘 모르겠습니다.
set apple to 1  -- apple: 1
set apple to eat() -- apple: 2

on eat()
get apple -- 오류가 발생합니다.
--set apple to 3 -- 위의 apple과는 다른 apple입니다.
return 2
end eat

스크립트의 첫째줄에서 apple이라는 변수를 만들었습니다. 그렇지만 eat()이라는 handler안에서 apple이라는 변수의 값을 요구하면 오류가 발생합니다. handler 안에서는 apple이라는 변수를 만든 적이 없기 때문입니다. handler 안에서 외부의 변수를 사용하고자 할 때에는 매개변수로서 handler에 전달되던가, 미리 그 변수를 전역변수로 만들어야 합니다.
set apple to 1
set apple to eat(apple)
on eat(apple)
set apple to 2
return apple
end eat
set apple to 1
global apple
my eat()

on eat()
get apple -- apple: 1
end eat
좀 더 정리된 문서를 올리도록 노력하겠습니다.

0 Comments:

댓글 쓰기

<< Home