How to construct a class in Lua

Source: Internet
Author: User
 1 function class(super, autoConstructSuper) 2     local classType = {}; 3     classType.autoConstructSuper = autoConstructSuper or (autoConstructSuper == nil); 4      5     if super then 6         classType.super = super; 7         local mt = getmetatable(super); 8         setmetatable(classType, { __index = super; __newindex = mt and mt.__newindex;}); 9     else10         classType.setDelegate = function(self,delegate)11             self.m_delegate = delegate;12         end13     end14 15     return classType;16 end17 18 19 function new(classType, ...)20     local obj = {};21     local mt = getmetatable(classType);22     setmetatable(obj, { __index = classType; __newindex = mt and mt.__newindex;});23     do24         local create;25         create =26             function(c, ...)27                 if c.super and c.autoConstructSuper then28                     create(c.super, ...);29                 end30                 if rawget(c,"ctor") then31                     obj.currentSuper = c.super;32                     c.ctor(obj, ...);33                 end34             end35 36         create(classType, ...);37     end38     obj.currentSuper = nil;39     return obj;40 end41 42 43 function delete(obj)44     do45         local destory =46             function(c)47                 while c do48                     if rawget(c,"dtor") then49                         c.dtor(obj);50                     end51               52                     c = getmetatable(c);53                     c = c and c.__index;                   54                 end55             end56         destory(obj);57     end58 end

 

How to construct a class in Lua

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.