LUA中點號和冒號的區別

Student = {};
Student.__index = Student;

function Student:new(name, age)
    local temp = {};
    setmetatable(temp, Student);
    temp.name = name;
    temp.age = age;
    return temp;
end


function Student:info()
    print(self.name, self.age);
--運行stu2時會報錯 -- print("name:" .. self.name .. " age:" .. self.age); end --輸出:stu1 10 stu1 = Student.new(nil, "stu1", 10); stu1:info(); --輸出:10 nil stu2 = Student.new("stu2", 10); stu2:info(); --輸出:nil stu3 stu3 = Student:new(nil, "stu3", 10); stu3:info(); --輸出:stu4 10 stu4 = Student:new("stu4", 10); stu4:info();

 

 

Student = {};
Student.__index = Student;

--此處作修改
function Student.new(name, age)
    local temp = {};
    setmetatable(temp, Student);
    temp.name = name;
    temp.age = age;
    return temp;
end


function Student:info()
    print(self.name, self.age);
end

--輸出:nil    stu1
stu1 = Student.new(nil, "stu1", 10);    
stu1:info();

--輸出:stu2    10
stu2 = Student.new("stu2", 10);    
stu2:info();

--輸出:table: 0037B200    nil
stu3 = Student:new(nil, "stu3", 10);    
stu3:info();

--輸出:table: 0037B200    stu4
stu4 = Student:new("stu4", 10);    
stu4:info();

--輸出:table: 0084B200    stu5
stu5 = Student:new("stu5");    
stu5:info();

--:stu6    10
stu6 = Student:new("stu6", 10);    
stu6.info(stu6);

 

 

Student = {};
Student.__index = Student;

function Student.new(name, age)
    local temp = {};
    setmetatable(temp, Student);
    temp.name = name;
    temp.age = age;
    return temp;
end


function Student:info()
    print(self.name, self.age);
end

function Student:message()
    print(self.name, self.age);
end

function Student.school()
    print("go to school!!!");
end

--聲明類時用點號:Student.new(name, age)
stu = Student:new("zhangsan", 10);
stu:info();    --輸出信息錯誤
stu.school();
--stu.message(); --報錯
stu.message(stu);--輸出信息錯誤

mes = Student.new("zhangsan", 10);
--mes.info();    --報錯
mes.info(mes);
mes.school();



--聲明類時用冒號:Student.new(name, age)
--stu = Student:new("zhangsan", 10);
--stu:info();
--stu.info(stu);
--stu.school();

--mes = Student.new(nil, "mes", 20);
--mes:message();
--mes.school();
相關文章
相關標籤/搜索