__index 연결을 이용한 단일 상속
부모 클래스를 메타테이블의 __index로 설정해 메서드를 상속합니다.
__index 연결을 이용한 단일 상속은(는) CoddyKit의 무료 Lua Academy 강의입니다. 이것은 4개 중 1번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 AI 튜터와 함께 브라우저에서 직접 실습할 수 있습니다. 이 강의는 Lua Academy 학습 경로의 일부이며, 진행 상황이 웹과 CoddyKit 앱에 동기화됩니다. Lua Academy 강의에는 총 4개의 강의가 포함되어 있습니다.
프로토타입 체인
단일 상속은 자식 클래스의 __index를 부모 클래스에 설정하는 방식으로 작동합니다. 자식에서 메서드를 찾지 못하면 Lua가 부모에서 찾습니다. 이렇게 프로토타입 체인이 만들어집니다.
local Base={}
Base.__index=Base
function Base.new() return setmetatable({},Base) end
function Base:greet() print("Hello from Base") end
local Child={}
Child.__index=Child
setmetatable(Child,{__index=Base}) -- Child inherits Base
function Child.new() return setmetatable({},Child) end
local c=Child.new()
c:greet() -- Hello from Base (inherited)메서드 해석 순서
인스턴스에서 메서드를 호출할 때는 다음 순서로 진행됩니다. (1) 인스턴스 테이블에서 찾고, (2) Child에서 찾고(__index를 통해), (3) Base에서 찾습니다(Child의 메타테이블 __index를 통해). 가장 먼저 일치하는 항목이 선택됩니다.
local Base={}
Base.__index=Base
function Base:who() print("I am Base") end
local Child={}
Child.__index=Child
setmetatable(Child,{__index=Base})
function Child:who() print("I am Child") end -- override
local b=setmetatable({},Base)
local c=setmetatable({},Child)
b:who() -- I am Base
c:who() -- I am Child (overrides)생성자 상속
자식 클래스는 부모 생성자를 호출하여 재사용하거나, 부모의 초기화를 확장하는 자체 생성자를 정의할 수 있습니다.
local Animal={}
Animal.__index=Animal
function Animal.new(name,sound)
return setmetatable({name=name,sound=sound},Animal)
end
function Animal:speak() print(self.name..": "..self.sound) end
local Dog={}
Dog.__index=Dog
setmetatable(Dog,{__index=Animal})
function Dog.new(name)
local self = Animal.new(name,"Woof")
return setmetatable(self,Dog)
end
function Dog:fetch(item) print(self.name.." fetches "..item) end
local d=Dog.new("Rex")
d:speak(); d:fetch("ball")계보 확인
메타테이블 체인을 따라 올라가 객체의 클래스가 지정된 기반 클래스에서 상속되었는지 확인할 수 있습니다. 이것이 Lua에서 instanceof가 작동하는 방식입니다.
local function instanceof(obj, cls)
local mt = getmetatable(obj)
while mt do
if mt == cls then return true end
mt = getmetatable(mt)
end
return false
end부모 호출
부모 클래스 테이블을 통해 직접 접근하여 재정의된 메서드의 부모 버전을 호출하세요.
local Base={}
Base.__index=Base
function Base:init(x) self.x=x end
function Base:value() return self.x end
local Child={}
Child.__index=Child
setmetatable(Child,{__index=Base})
function Child:init(x,y)
Base.init(self,x) -- call parent
self.y=y
end
function Child:value() return Base.value(self)+self.y end
local c=setmetatable({},Child)
c:init(3,4)
print(c:value()) -- 7깊은 체인
3단계 계층 구조를 만드세요: A → B → C. 메서드 조회는 메서드를 찾을 때까지 전체 체인을 탐색합니다.
local A={}
A.__index=A
function A:aMethod() print("A method") end
local B={}
B.__index=B
setmetatable(B,{__index=A})
function B:bMethod() print("B method") end
local C={}
C.__index=C
setmetatable(C,{__index=B})
local c=setmetatable({},C)
c:bMethod() -- from B
c:aMethod() -- from A필드 재정의
인스턴스는 필드를 직접 설정하여 클래스 수준의 필드를 재정의할 수 있습니다. 클래스 필드가 변경되는 것이 아니라 해당 인스턴스에서만 가려집니다.
local Creature={}
Creature.__index=Creature
Creature.hp=100
Creature.speed=10
function Creature.new()
return setmetatable({},Creature)
end
local fast=Creature.new()
fast.speed=20 -- override for this instance
local normal=Creature.new()
print(fast.speed,normal.speed,Creature.speed) -- 20 10 10클래스 수준 상속
setmetatable(Child, {__index=Parent})를 설정하면 클래스 수준의 조회가 부모로 이어집니다. 따라서 Child.classMethod()는 재정의되지 않은 경우 부모 클래스의 메서드를 찾습니다.
local Vehicle={}
Vehicle.__index=Vehicle
Vehicle.maxSpeed=120
function Vehicle.describe() print("Vehicle") end
local Car={}
Car.__index=Car
setmetatable(Car,{__index=Vehicle})
Car.describe() -- Vehicle (inherited class method)
print(Car.maxSpeed) -- 120 (inherited class field)초기화 체인
올바르게 초기화하려면 자식 생성자가 부모 생성자를 호출하여 부모 상태가 설정되도록 해야 합니다. 계층 구조를 따라 초기화를 연결하세요.
local Base={}
Base.__index=Base
function Base:_init(name) self.name=name end
local Mid={}
Mid.__index=Mid
setmetatable(Mid,{__index=Base})
function Mid:_init(name,level)
Base._init(self,name)
self.level=level
end
local Top={}
Top.__index=Top
setmetatable(Top,{__index=Mid})
function Top.new(name,level,role)
local self=setmetatable({},Top)
Mid._init(self,name,level)
self.role=role
return self
end
local t=Top.new("Alice",5,"admin")
print(t.name,t.level,t.role)추상 기반 클래스
구현되지 않은 메서드가 오류를 발생시키도록 기반 클래스를 만드세요. 하위 클래스는 이러한 메서드를 재정의해야 합니다. 이는 Lua의 동적 유형 시스템에서 인터페이스 계약을 강제합니다.
local Serializer={}
Serializer.__index=Serializer
function Serializer:encode(data)
error(self._type.." must implement encode()",2)
end
function Serializer:decode(str)
error(self._type.." must implement decode()",2)
end
local JSONSerializer={_type="JSON"}
setmetatable(JSONSerializer,{__index=Serializer})
function JSONSerializer:encode(data)
return "{"..tostring(data.key).."}"
end
local j=setmetatable({_type="JSON"},JSONSerializer)
print(j:encode({key="val"}))상속 질문
Lua에서 단일 상속을 가능하게 하는 것은 무엇인가요?
복습: 단일 상속
메서드를 상속하려면 setmetatable(Child, {__index = Parent})를 설정하세요. __index 체인이 자동 위임을 제공합니다. Child에 메서드를 정의하여 재정의하고, Parent.method(self)로 부모를 명시적으로 호출하세요.
자주 묻는 질문
“__index 연결을 이용한 단일 상속” 강의는 무료인가요?
네 — “__index 연결을 이용한 단일 상속” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 Lua Academy 강의 전체를 잠금 해제할 수 있습니다. Lua Academy 강의에는 총 4개의 강의가 포함되어 있습니다.
“__index 연결을 이용한 단일 상속”에서 뭘 배우나요?
부모 클래스를 메타테이블의 __index로 설정해 메서드를 상속합니다. 브라우저에서 직접 실행하는 실습 코드로 Lua Academy을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.
Lua Academy을(를) 시작하는 데 경험이 필요한가요?
사전 경험은 필요하지 않습니다. CoddyKit의 Lua Academy은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 4개 중 1번째 강의입니다.
“__index 연결을 이용한 단일 상속” 강의는 얼마나 걸리나요?
대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.
이 Lua Academy 강의에서 코드를 작성하고 실행할 수 있나요?
네. 모든 Lua Academy 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.
이 강의의 모든 강의
- __index 연결을 이용한 단일 상속
- super로 부모 메서드 호출하기
- 믹스인 패턴
- 재정의와 다형성