티스토리 뷰

http://lua-users.org/wiki/ObjectOrientationTutorial
이 문서를 번역한 자료입니다.

Representation of classes in Lua
Lua의 대표 클래스들 

Lua has no built-in notion of "classes" for use in object-oriented programming.
Lua는 객체지향 프로그래밍을 위한 클래스 개념을 기본으로 내장하고 있지 않습니다.
However, we can simulate many features of the classes of other languages by using just the tables and metamethods discussed previously (MetamethodsTutorial).
그러나, 우리는 다른 언어들의 많은 클래스 기능들을 table과 metamethod들을 이용하여 구현할 수 있습니다.
(메타메소드에 대한 내용은 이전에 논의되었습니다. 링크에 있음.)
To declare a class in Lua, we will need (1) a constructor (String:new below), (2) a class method table (String), and (3) a ''class metatable' (mt).
Lua에서 클래스를 선언하기 위해서, 우리는 먼저 (1) 생성자, (2) 클래스 함수, (3) 클래스 메타테이블이 필요합니다. 

The method table is an ordinary table containing functions.
메소드 테이블은 보통의 함수를 포함하는 테이블입니다.
These functions constitute the methods of the class.
이 함수들은 클래스의 메소드들로 구성되어 있습니다.
The constructor is a function which, when called, sets up a new table (our instance object) and attaches the class metatable to it.
생성자는 호출되었을 때 새로운 테이블을 생성하고 메타테이블로 설정해주는 함수입니다.
Finally, the metatable is simply a metatable which redirects unrecognized events to the class method table (as well as possibly handling events itself).
마지막으로, 그 메타테이블은 클래스의 메소드 테이블에서 인식되지 않는 이벤트들을 다루기 위한 것입니다.
(스스로 이벤트들을 다룰 수 있도록) -- 이 부분 번역이 조금 이상하네요....

The following is a rearranged version of the String example from theMetamethodsTutorial:
아래는 이전의 MetamethodsTutorial에서 사용했던 String 예제입니다. 

> String = {}
> mt = {}
>
> function String:new(s)
>>   return setmetatable({ value = s or '' }, mt)
>> end
>
> function String:print()
>>   print(self.value)
>> end
>
> mt.__add = function (a,b) return String:new(a.value..b.value) end
> mt.__mul = function (a,b) return String:new(string.rep(a.value, b)) end
> mt.__index = String -- redirect queries to the String table
>
> s = String:new('hello ')
> s:print()
hello
> a = ((String:new('hello ') + String:new('Lua user. '))*2)
> a:print()
hello Lua user. hello Lua user.
We create a table String to hold our String class methods. Instead of having a functional interface (e.g. String.print(s)) we would like to call the object, e.g. s:print().
우리는 테이블을 만들었고 String 클래스 메소드들로 String을 만듭니다.
대신 함수적 인터페이스를 갖습니다(String.print(s) 같은).
우리가 이 객체를 호출하려면 s:print() 이렇게 사용하면 됩니다.
--?? 조금 이상합니다. 어찌되었든 클래스를 만들 수 있고 이렇게 호출하면 됩니다. 라는 내용인 것 같습니다.

It is also possible to eliminate mt and use String instead for all cases where mt is used.
mt를 제거하는 것도 가능하고 String 클래스를 이용하여 mt가 어디에 쓰이고 있는지도 알 수 있습니다.
--?? 조금 이해가 안되네요.

Method calling conventions
메소드 호출 방법 

Note in the example that we use the : operator to declare and call the class methods.
우리가 사용하는 예제에서 : 연산자로 메소드들을 선언하고 호출했습니다.
This is syntactic sugar for String.print(s), or s.print(s), i.e. the colon makes Lua put the object we are calling as the first parameter in the function call.
이것은 구문론의 감초인데 String.print(s) 혹은 s.print(s), 즉 콜론으로 Lua 오브젝트의 함수를 호출할 때 첫번째 파라미터를 사용합니다.
The following all have the same result by different methods:
아래를 보면 다른 방법들이지만 같은 결과를 보여줍니다. 

> s.print(s)       -- use __index metamethod but no sugar
hello
> s:print()        -- use __index metamethod and sugar
hello
> String.print(s)  -- call String directly, no metamethod or sugar
hello

Method declarations
함수 선언 

Likewise there is syntactic sugar for method declarations.
마찬가지로 구문론의 감초는 함수 선언에도 있습니다.
Regardless how it is declared, a method expects that the first argument passed in is the object to be acted on.
어떻게 선언하던 관계 없이, 함수는 첫번째 인자가 객체로 넘겨지면 그것이 실행됩니다. --?? 정확하지 않음...
If a dot is used (i.e. t.foo(self, args)) we declare self ourselves.
. 연산자가 사용되면( t.foo(self, args 처럼 ) 그것 스스로 그것을 선언합니다.
If a colon is used (i.e. t:foo(args)self will be declared automatically for us.
: 연산자가 사용되면 ( t:foo(args) 처럼 ) self는 우리를 위해 자동으로 선언될겁니다.

> t = {}
> function t.foo(self,x) print(self,x) end  -- no sugar, explicit self
> function t:foo2(x) print(self,x) end      -- sugar and magic self
>
> t.foo(t,1)         -- is the same as...
table: 0035D830 1
> t:foo2(1)          -- shorthand for above
table: 0035D830 1
And reversed:
> t:foo(1)           -- the same as...
table: 0035D830 1
> t.foo2(t,1)
table: 0035D830 1

Notes on the convention
방법에 대한 주석 

The colon calling and method declaration styles are shortcuts, not a rigid style of programming; As the examples show, you can mix and match styles.
: 호출과 함수 선언 방식은 엄격한 프로그래밍 방식의 지름길이 아닙니다.
예제에서 보여진 것과 같이, 우리는 스타일에 맞게 그것을 섞어서 써도 됩니다.

Explicitly declaring self
명시적 선언 

If you don't like the automatic appearance of the self argument in function declarations you might choose the following style, where self is explicitly declared:
만약 당신이 자동으로 self 인자가 함수에 선언되지 않도록 하고 싶다면 다음의 방식을 따라하십시오.
self는 명시적 선언되어 있습니다. 

> foo = { value = 0 }
> function foo.add(self, x) self.value = self.value+x end
> function foo.print(self) print (self.value) end
> foo:print()
0
> foo:add(123)
> foo:add(99)
> foo:print()
222

Defining functions in a table constructor
테이블 생성자에 함수 정의하기 

Please note that if you declare your class methods in a table constructor you'll have to declare self explicitly as using the colon is not an option.
만약 당신이  클래스 메소드들을 테이블 생성자에서 정의하고 콜론을 쓰고 싶다면 당신은 반드시 self를 명시적 선언해야만 합니다.

> foo = {
>>     value = 0,
>>     print = function(self) print(self.value) end,
>>     add = function(self, x) self.value = self.value + x end
>> }
>
> foo:print()
0
> foo:add(77)
> foo:print()
77

See Also

  • ObjectOrientedProgramming - links and discussions on using object oriented programming techniques in Lua.
    위 링크를 따라가면 객체 지향 프로그래밍 기술에 대한 논의가 있습니다. 

 
저번 것 보다 발번역이 더 심한 것 같군요....
교과서적인 문장들이 아니라 위키인지라 사람들이 막 써놓아서 잘 번역이 안됩니다.
제 영어실력이 후달리는 문제도 있지만은.... 아무튼 앞으로도 번역한 것에 대해 많이 태클 걸어주시고 조언 해주시면
글 내용을 수정해나가면서 많은 분들에게 도움을 줄 수 있을 것 같습니다. 
댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday