super로 부모 메서드 호출하기
협력적 초기화를 위해 기본 클래스 메서드를 명시적으로 호출합니다.
super로 부모 메서드 호출하기은(는) CoddyKit의 무료 Lua Academy 강의입니다. 이것은 4개 중 2번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 AI 튜터와 함께 브라우저에서 직접 실습할 수 있습니다. 이 강의는 Lua Academy 학습 경로의 일부이며, 진행 상황이 웹과 CoddyKit 앱에 동기화됩니다. Lua Academy 강의에는 총 4개의 강의가 포함되어 있습니다.
부모 호출이 필요한 이유
자식이 부모 메서드를 재정의했지만 부모의 로직도 필요하다면 부모 메서드를 명시적으로 호출합니다. Lua에는 super 키워드가 없으므로 부모 테이블을 직접 참조합니다: Parent.method(self, args).
local Base={}
Base.__index=Base
function Base:describe()
return "Base[name="..self.name.."]"
end
local Child={}
Child.__index=Child
setmetatable(Child,{__index=Base})
function Child:describe()
local parentDesc = Base.describe(self) -- super call
return parentDesc .. " + Child[extra=true]"
end
local c=setmetatable({name="X"},Child)
print(c:describe())생성자에서 부모 호출
자식 생성자는 Parent.new() 또는 Parent._init(self,...)를 통해 부모 생성자를 호출합니다. 이렇게 하면 모든 자식 인스턴스에서 부모의 초기화가 실행됩니다.
local Animal={}
Animal.__index=Animal
function Animal._init(self,name,sound)
self.name=name; self.sound=sound; self.alive=true
end
local Dog={}
Dog.__index=Dog; setmetatable(Dog,{__index=Animal})
function Dog.new(name,breed)
local self=setmetatable({},Dog)
Animal._init(self,name,"Woof") -- super init
self.breed=breed
return self
end
local d=Dog.new("Rex","Lab")
print(d.name,d.sound,d.breed)협력적 초기화
깊은 계층 구조에서는 각 단계가 자신의 필드만 초기화하고 부모의 init을 호출합니다. 이렇게 하면 각 클래스가 자신의 필드에 대해서만 책임을 지게 됩니다.
local A={}
function A._init(self,x) self.x=x end
local B={}
function B._init(self,x,y) A._init(self,x); self.y=y end
local C={}
C.__index=C
function C.new(x,y,z)
local self=setmetatable({},C)
B._init(self,x,y)
self.z=z
return self
end
local c=C.new(1,2,3)
print(c.x,c.y,c.z) -- 1 2 3super 래퍼
super(self) 도우미를 만들어 self와 함께 부모 메서드를 호출하는 프록시 객체를 반환하도록 하세요. 이렇게 하면 Parent.method(self, ...)보다 구문이 깔끔해집니다.
local function super(self)
local mt = getmetatable(getmetatable(self).__index)
if mt then
return setmetatable({}, {__index=function(_,k)
local parentCls = mt.__index or mt
return function(...) return parentCls[k](self,...) end
end})
end
end
print("super() helper pattern shown")여러 단계
상속 단계가 여러 개라면 각 단계가 바로 위 부모를 호출합니다. 체인은 자동으로 이어집니다.
local L1={} L1.__index=L1
function L1:intro() return "L1" end
local L2={} L2.__index=L2
setmetatable(L2,{__index=L1})
function L2:intro() return L1.intro(self).."+L2" end
local L3={} L3.__index=L3
setmetatable(L3,{__index=L2})
function L3:intro() return L2.intro(self).."+L3" end
local obj=setmetatable({},L3)
print(obj:intro()) -- L1+L2+L3메서드 확장
부모 메서드를 확장하려면 부모 버전을 호출한 다음 추가 동작을 넣으세요. 이는 공식적인 AOP 프레임워크 없이 구현하는 "호출 전" 또는 "호출 후" 조언입니다.
local Logger={} Logger.__index=Logger
function Logger:log(msg) print("[LOG] "..msg) end
local TimedLogger={} TimedLogger.__index=TimedLogger
setmetatable(TimedLogger,{__index=Logger})
function TimedLogger:log(msg)
local ts=os.date("%H:%M:%S")
Logger.log(self,"["..ts.."] "..msg) -- augment
end
local tl=setmetatable({},TimedLogger)
tl:log("Server started")부모 호출의 함정 피하기
부모 호출에는 getmetatable(self).__index가 아니라 항상 정확한 부모 클래스 이름을 사용하세요. 메타테이블 조회는 진정한 부모가 아닌 중간 클래스를 반환할 수 있습니다. 명확성과 정확성을 위해 명시적으로 작성하세요.
-- Correct: explicit parent reference
function Child:init(x)
Base.init(self, x) -- explicit, clear
end
-- Fragile: uses metatable lookup
function Child:initBad(x)
local parent = getmetatable(getmetatable(self).__index)
-- This may not be Base if hierarchy changes!
end
print("Be explicit with parent class references")__tostring에서 부모 호출
자식에서 __tostring을 재정의하면서 부모의 표현도 포함하면 완전한 설명을 만들 수 있습니다.
local Base={}
Base.__index=Base
Base.__tostring=function(self) return "Base("..self.name..")" end
local Child={}
Child.__index=Child
setmetatable(Child,{__index=Base})
Child.__tostring=function(self)
local baseStr = Base.__tostring(self)
return baseStr.." + Child(level="..self.level..")"
end
local c=setmetatable({name="X",level=5},Child)
print(tostring(c)) -- Base(X) + Child(level=5)보호된 템플릿 메서드
템플릿 메서드 패턴에서는 기반 클래스가 추상 단계 호출을 포함한 알고리즘의 뼈대를 정의하고, 하위 클래스가 그 단계를 구현합니다.
local Processor={} Processor.__index=Processor
function Processor:run(data)
data = self:preProcess(data)
data = self:process(data)
return self:postProcess(data)
end
function Processor:preProcess(d) return d end
function Processor:postProcess(d) return d end
function Processor:process(d) error("implement process()") end
local Upper={} Upper.__index=Upper
setmetatable(Upper,{__index=Processor})
function Upper:process(d) return d:upper() end
local p=setmetatable({},Upper)
print(p:run("hello")) -- HELLO부모 호출 관례
관례상 내부에서만 사용하는 초기화 함수에는 _를 접두사로 붙이고(예: _init), 최상위 생성자에서만 공개 new()를 제공합니다. 이렇게 하면 상속 체인을 깔끔하게 유지할 수 있습니다.
-- Convention summary:
-- Animal._init(self, ...) -- used for super calls
-- Dog.new(...) -- only public constructor
-- Never call Dog._init from outside
local Foo={} Foo.__index=Foo
function Foo._init(self,x) self.x=x end
function Foo.new(x)
return setmetatable({},Foo):_init(x) or
(function() local s=setmetatable({},Foo); Foo._init(s,x); return s end)()
end
print("Convention: _init for super, new() for public")부모 호출 질문
Lua에서 부모 메서드를 어떻게 호출하나요?
복습: 부모 호출
부모 메서드는 항상 명시적인 클래스 참조로 호출하세요: Parent.method(self, ...). 상속 단계 전체에서 협력적으로 생성자를 호출하려면 _init 관례를 사용하세요.
자주 묻는 질문
“super로 부모 메서드 호출하기” 강의는 무료인가요?
네 — “super로 부모 메서드 호출하기” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 Lua Academy 강의 전체를 잠금 해제할 수 있습니다. Lua Academy 강의에는 총 4개의 강의가 포함되어 있습니다.
“super로 부모 메서드 호출하기”에서 뭘 배우나요?
협력적 초기화를 위해 기본 클래스 메서드를 명시적으로 호출합니다. 브라우저에서 직접 실행하는 실습 코드로 Lua Academy을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.
Lua Academy을(를) 시작하는 데 경험이 필요한가요?
사전 경험은 필요하지 않습니다. CoddyKit의 Lua Academy은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 4개 중 2번째 강의입니다.
“super로 부모 메서드 호출하기” 강의는 얼마나 걸리나요?
대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.
이 Lua Academy 강의에서 코드를 작성하고 실행할 수 있나요?
네. 모든 Lua Academy 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.
이 강의의 모든 강의
- __index 연결을 이용한 단일 상속
- super로 부모 메서드 호출하기
- 믹스인 패턴
- 재정의와 다형성