Lua 에서 대상 지향 인 스 턴 스 구현
local _class={}
 
function class(super)
	local class_type={}
	class_type.ctor=false
	class_type.super=super
	class_type.new=function(...) 
			local obj={}
			do
				local create
				create = function(c,...)
					if c.super then
						create(c.super,...)
					end
					if c.ctor then
						c.ctor(obj,...)
					end
				end
 
				create(class_type,...)
			end
			setmetatable(obj,{ __index=_class[class_type] })
			return obj
		end
	local vtbl={}
	_class[class_type]=vtbl
 
	setmetatable(class_type,{__newindex=
		function(t,k,v)
			vtbl[k]=v
		end
	})
 
	if super then
		setmetatable(vtbl,{__index=
			function(t,k)
				local ret=_class[super][k]
				vtbl[k]=ret
				return ret
			end
		})
	end
 
	return class_type
end이제 어떻게 사용 하 는 지 봅 시다.
base_type=class()		--        base_type
 
function base_type:ctor(x)	--    base_type      
	print("base_type ctor")
	self.x=x
end
 
function base_type:print_x()	--          base_type:print_x
	print(self.x)
end
 
function base_type:hello()	--           base_type:hello
	print("hello base_type")
end이상 은 기본 적 인 class 정의 문법 으로 lua 의 프로 그래 밍 습관 을 완전히 호 환 합 니 다.나 는 구조 함수 의 이름 으로 ctor 라 는 단 어 를 추가 했다.다음은 어떻게 계승 하 는 지:
test=class(base_type)	--       test     base_type
 
function test:ctor()	--    test      
	print("test ctor")
end
 
function test:hello()	--    base_type:hello   test:hello
	print("hello test")
end이제 한번 해 보 세 요.
a=test.new(1)	--     ,base_type ctor   test ctor 。           。
a:print_x()	--    1 ,      base_type       。
a:hello()	--    hello test ,        。 이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
다양한 언어의 JSONJSON은 Javascript 표기법을 사용하여 데이터 구조를 레이아웃하는 데이터 형식입니다. 그러나 Javascript가 코드에서 이러한 구조를 나타낼 수 있는 유일한 언어는 아닙니다. 저는 일반적으로 '객체'{}...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.