루아 실현 클래스와 계승

1527 단어 lua 클래스 상속
하나의 예를 통해 설명하다

local Person = {name, age} 
Person.__index = Person

function Person:talk(word) 
	print(self.name.." say "..word)
end

function Person:setAge(age) 
	self.age = age
end

function Person:getAge()
	return self.age
end

function Person:new(name, age) 
	local p = {}		
	setmetatable(p, Person)
	p.name = name
	p.age = age
	return p
end

return Person

local Student = {}
local Person = require 'Person'
setmetatable(Student, Person)
Student.__index = Student

function Student:new(name, age, score) 
	local self = {}
	self = Person:new(name, age)
	setmetatable(self, Student)
	self.score = score
	return self
end

function Student:setScore(score)
	self.score = score
end

function Student:getScore()
	return self.score
end

return Student

local Person = require 'Person'
local pa = Person:new("tom", 18);
pa:talk("hello");

local Student = require 'Student'
local st = Student:new("jim", 19, 100);
print(st:talk('nihao'));
print(st:getScore());

참고 자료:
http://wuzhiwei.net/lua_make_class/
http://blog.sina.com.cn/s/blog_6b9d508001015qd3.html

좋은 웹페이지 즐겨찾기