I posted an article that is out of standard.Article, Claiming that the Lua singleton object can be implemented using the method described in this article.
It can be a reality, but it is too ugly, which does not reflect the beauty of Lua, but also comes with naming pollution. After reading FP, I came up with a more elegant implementation solution:
Hello ={}</P> <p> function Hello: New () -- Private method. <br/> local store = nil </P> <p> return function (Self) <br/> If store then return store end </P> <p> Print "create. "-- for test. <br/> Local o ={}< br/> setretriable (O, self) <br/> self. _ Index = self </P> <p> store = O <br/> return o <br/> end </P> <p> hello. instance = Hello: New () -- implement Single Instance Object. </P> <p> -- test following <br/> Local Hello = Hello: instance () --> create. <br/> Local hellohello = Hello: instance () -- no output </P> <p> local hi = Hello <br/> local hi = Hi: instance () -- the same with Hello: instance
Use closures to create more elegant implementations.
Oop implemented through meta-tables cannot implement encapsulation, so new is a private method that can only rely onProgramThe employee consciously ......
ASIDE: to implement encapsulated Oop, we can only implement it through closures. This is mentioned in Lua program design, but this method is not recommended by the author for unknown reasons. I guess it is probably because it cannot share the class method. Each object has all the data of the class and copies the method.