Lua Study Notes 4: class and integration implementation
Source: Internet
Author: User
-- Implementation of classes in Lua
-------------------------------- Base class ----------------------------
Classbase = {x = 0, y = 0} -- X, Y is the member variable of the class.
Classbase. _ Index = classbase -- this statement is used to redefine the meta-Table index, which must have
-- Simulate the constructor, which is generally named new ()
Function classbase: New (x, y)
Local Self ={} -- initialize the object itself
Setretriable (self, classbase) -- must have
Self. x = x
Self. Y = y
Return self
End
Function classbase: Show () -- member function of the class
Print (self. X, self. Y)
End
-- Basic test code
Obja = classbase: New () -- call to create a class object for a function
Obja: Show () -- call class Method
Print (obja. X, obja. y) -- member variable of the struct class
-- # Lua allows you to add an additional parameter self in a method definition using a colon,
-- # In this way, an error is returned when calling sequence BJA. Show (). Self is nil.
-- # Print (obja: X, obja: Y) Error
-------------------------------- Inheritance: derived class ----------------------------
Classderived = {z = 0} -- add member variables
Setretriable (classderived, classbase) -- set the type to classbase.
Classderived. _ Index = classderived -- same as the class definition, the index value indicates itself.
-- Constructor
Function classderived: New (x, y, z)
Local Self = {}
Self = classbase: New (x, y) -- set the object itself as a parent class, which is equivalent to calling the constructor of the parent class.
Setretriable (self, classderived) -- set the object metadata table to classderived
Self. z = z -- new attribute initialization. If not, it will be declared as 0
Return self
End
-- Override the parent class Method
Function classderived: Show ()
Print (self. X, self. Y, self. Z)
End
-- Add Method
Function classderived: showsum ()
Print (self. x + self. Y + self. Z)
End
-- Test code of a derived class
Objb = classderived: New (, 3) -- call to create a Class Object
Objb: Show () -- call the rewrite method, reflecting Polymorphism
Objb: showsum () -- call the newly added Method
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