Lua 没有内置对 OO 的支持,但它允许您自己构建它。您能否分享一些可以实现 OO 的方法?
请为每个答案写一个例子。如果您有更多示例,请发布另一个答案。
最佳答案
为了快速而肮脏的oo实现,我做了类似的事情 -
function newRGB(r,g,b)
return {
red=r;
green=g;
blue=b;
name='';
setName = function(self,name)
self.name=name;
end;
getName = function(self)
return self.name;
end;
tostring = function(self)
return self.name..' = {'..self.red..','..self.green..','..self.blue..'}'
end
}
end
然后可以像 -
blue = newRGB(0,0,255);
blue:setName('blue');
yellow = newRGB(255,255,0);
yellow:setName('yellow');
print(yellow:tostring());
print(blue:tostring());
对于更全功能的方法,我将使用 eemrevnivek 提到的 oo 库。还可以找到一个简单的类函数here这介于图书馆满载和快速肮脏之间。
关于oop - 如何在 Lua 中实现面向对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4799078/