* 정의

 

메타테이블(metatable)은 키 세트(key set)와 관련 메타 메소드의 도움으로 메타테이블과 연결된 테이블 동작에 대한 수정을 도와주는 테이블이다.

 

 

* 사용 이유

 

다음과 같은 기능을 활용하기 위해 사용된다.

 

  • 테이블 연산자(operator)에 기능을 변경 및 추가할 수 있다.
  • 테이블에서 정의되지 않은 키가 들어왔을 때 메타테이블에 존재하는 __index를 통해 메타테이블을 조회할 수 있다.
  • 클래스의 상속을 구현할 수 있다.

 

* 동작 방식

 

- setmatatable, getmatatable

 

메타테이블을 사용하기 위한 두 가지 중요한 메소드를 제공한다.

 

  • setmetatable(table, metatable) : 해당 테이블의 메타테이블을 설정하기 위해 사용된다.
  • getmetatable(table) - 해당 테이블의 메타테이블을 가져오기 위해 사용된다.

 

setmetatable은 다음과 같이 사용할 수 있다.

-- mytable = setmetatable({},{})
mytable = {}
mymetatable = {}
setmetatable(mytable,mymetatable)

 

 

- __index

 

https://create-new-worlds.tistory.com/363

 

[Lua] __index

* 정의 __index는 테이블의 메타테이블 안에 정의할 수 있는 메타메소드이다. 만약 테이블에서 정의되지 않은 값을 바로 nil로 반환하지 않고 추가로 __index 메타메소드를 확인하여 적절한 값을 반

create-new-worlds.tistory.com

 

 

- __newindex

 

https://create-new-worlds.tistory.com/369

 

[Lua] __newindex

* 정의 __newindex는 테이블의 메타테이블 안에 정의할 수 있는 메타메소드이다. 테이블에서 테이블에 정의되어 있지 않은 새로운 키를 할당하려고 할 때 해당 테이블의 메타테이블에서 __newindex가

create-new-worlds.tistory.com

 

 

- operator 메타메소드, 기타 메타메소드

 

+, -, *, /, % 등 수 많은 연산자에 대해서도 행동을 정의할 수 있다. 연산자 오버로딩과 비슷하게 생각하면 된다.

 

그 외에도 메소드의 동작을 정의할 수 있는 __call 메타메소드, print 에서의 동작 방식을 변경할 수 있는 __tostring등이 존재한다.

 

자세한 내용은 여기서 볼 수 있다.

https://www.tutorialspoint.com/lua/lua_metatables.htm#

 

Lua - Metatables

Lua - Metatables A metatable is a table that helps in modifying the behavior of a table it is attached to with the help of a key set and related meta methods. These meta methods are powerful Lua functionality that enables features like − Changing/adding

www.tutorialspoint.com

 

+ Recent posts