Lua 面向对象
系统讲解 Lua 如何借助 table、function 与元表 __index 原型链实现面向对象编程,涵盖冒号 : 隐式 self 语法糖、构造函数、继承、方法重写、多态以及封装与抽象。
学完这一章,你能够
- 系统讲解 Lua 如何借助 table、function 与元表 __index 原型链实现面向对象编程,涵盖冒号 : 隐式 self 语法糖、构造函数、继承、方法重写、多态以及封装与抽象。
面向对象四大特征与 Lua 原型对象模型
面向对象编程(OOP)围绕封装、继承、多态与抽象四大核心特征组织软件架构,广泛存在于 C++、Java、Objective-C、Smalltalk、C# 与 Ruby 等语言中。虽然 Lua 并未在语法层内置 `class` 关键字,但依靠 `table`、一等函数与元表机制即可干净地实现基于原型的面向对象体系。
在 Lua 中,一张“类表”(如 `Person = {name = "", age = 0}`)保存默认属性和成员函数;构造函数 `Person:new(name, age)` 创建新表 `local obj = {}`,执行 `setmetatable(obj, self)` 与 `self.__index = self`,使实例在自身未命中字段时沿 `__index` 自动回退查找类表的方法与默认属性。定义和调用方法时使用的冒号语法糖 `obj:introduce()` 本质等价于 `obj.introduce(obj)`,它会自动将调用者自身作为隐式首参数 `self` 传入。
以 `Rectangle` 类为例:属性 `area`、`length`、`breadth` 存储在各个实例表中,通过 `Rectangle:new(nil, 5, 10)` 创建对象并在初始化阶段分配内存;读取数据成员使用点号 `r.length`,调用成员方法使用冒号 `r:printArea()`。不同实例拥有各自独立的状态表,同时共享类表上的方法定义,如 `rect1` 与 `rect2` 分别输出面积 `50` 和 `21`。
原型继承、构造函数与方法重写及多态
Lua 中的继承通过将子类的元表指向父类构成多层 `__index` 原型链来实现。执行 `Square = Rectangle:new()` 即可让 `Square` 继承 `Rectangle` 的属性与 `printArea()` 方法;随后重写 `Square:new(o, side)` 将 `length` 与 `breadth` 统一设为边长 `side` 并计算面积,使 `Square:new(nil, 4):printArea()` 复用父类方法并输出 `16`。
当子类定义与父类同名的方法(方法重写)时,查找链会优先命中子类表中的新实现,自然形成**多态**派发。例如 `Dog = Animal:new()` 重写 `Dog:speak()` 后,`animal:speak()` 输出 `"Generic Animal makes a sound."` 而 `dog:speak()` 输出 `"Buddy barks."`;同样地,`Student = Person:new()` 重写 `greet()` 后,对 `person2` 与 `student2` 统一调用 `:greet()` 会按对象实际原型分别输出各自的问候语。
封装与抽象的 Lua 实践
封装强调将数据与操作绑定并受控访问:在基础表对象中可约定通过 `setName`/`getName` 读写属性,若需强隐藏内部状态则可借助闭包私有表(仅返回对外方法表)或元表 `__index`/`__newindex` 拦截非法字段访问。抽象则在此基础上进一步对外只暴露简洁的高层接口(如 `showInfo()`),将内部字段组织和格式化细节隐藏在方法实现之后。
离线校验原型表对象、冒号 self 语法糖、Square/Dog 继承重写、多态与闭包封装
"""Offline Lua 5.4 semantic verification lab for Chapter 22 (object-oriented)."""
import json
VERSION = "CPython 3.12.14 offline Lua 5.4 semantic verifier (lua interpreter absent)"
class ProtoObject:
"""Faithful Lua table + metatable(__index) prototype object model."""
def __init__(self, fields=None, proto=None):
self.fields = dict(fields or {})
self.proto = proto
def get(self, key):
if key in self.fields:
return self.fields[key]
if self.proto is not None:
return self.proto.get(key)
return None
def set(self, key, val):
self.fields[key] = val
def call_colon(self, method_name, *args):
"""Syntactic sugar `obj:method(...)` == `obj.method(obj, ...)`."""
fn = self.get(method_name)
return fn(self, *args)
def case_prototype_class_and_colon_sugar():
Person = ProtoObject({"name": "", "age": 0})
def person_new(cls, name, age):
obj = ProtoObject({"name": name, "age": age}, proto=cls)
return obj
def person_introduce(self):
return f"My name is {self.get('name')} and I am {self.get('age')} years old."
Person.set("new", person_new)
Person.set("introduce", person_introduce)
p1 = Person.call_colon("new", "Alice", 30)
via_colon = p1.call_colon("introduce")
# Explicit dot call passing self manually yields the exact same result
via_dot = p1.get("introduce")(p1)
expected = {
"via_colon": "My name is Alice and I am 30 years old.",
"colon_equals_dot_with_self": True,
"dot_field_access": ["Alice", 30],
}
actual = {
"via_colon": via_colon,
"colon_equals_dot_with_self": via_colon == via_dot,
"dot_field_access": [p1.get("name"), p1.get("age")],
}
return {
"name": "prototype_class_and_colon_sugar",
"summary": "校验表+元表 __index 模拟 Person 类及冒号语法糖 obj:method() 与 obj.method(obj) 等价性",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def case_rectangle_and_square_inheritance():
Rectangle = ProtoObject({"area": 0, "length": 0, "breadth": 0})
def rect_new(cls, o=None, length=0, breadth=0):
obj = o if o is not None else ProtoObject()
obj.proto = cls
obj.set("length", length or 0)
obj.set("breadth", breadth or 0)
obj.set("area", obj.get("length") * obj.get("breadth"))
return obj
def rect_print_area(self):
return f"矩形面积为 {self.get('area')}"
Rectangle.set("new", rect_new)
Rectangle.set("printArea", rect_print_area)
Square = Rectangle.call_colon("new")
def square_new(cls, o=None, side=0):
obj = o if o is not None else ProtoObject()
obj.proto = cls
s = side or 0
obj.set("length", s)
obj.set("breadth", s)
obj.set("area", s * s)
return obj
Square.set("new", square_new)
r1 = Rectangle.call_colon("new", None, 5, 10)
r2 = Rectangle.call_colon("new", None, 7, 3)
sq = Square.call_colon("new", None, 4)
expected = {
"rect1_area": "矩形面积为 50",
"rect2_area": "矩形面积为 21",
"square_inherits_printArea": "矩形面积为 16",
}
actual = {
"rect1_area": r1.call_colon("printArea"),
"rect2_area": r2.call_colon("printArea"),
"square_inherits_printArea": sq.call_colon("printArea"),
}
return {
"name": "rectangle_and_square_inheritance",
"summary": "校验 Square 原型继承 Rectangle,重写构造函数同时沿原型链复用 printArea 方法",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def case_method_override_and_polymorphism():
Animal = ProtoObject({"name": "Unknown"})
Animal.set("new", lambda cls, o=None, name="Unknown": ProtoObject({"name": name or "Unknown"}, proto=cls))
Animal.set("speak", lambda self: f"{self.get('name')} makes a sound.")
Dog = Animal.call_colon("new")
Dog.set("new", lambda cls, o=None, name="Unknown", breed="Unknown": ProtoObject({"name": name, "breed": breed}, proto=cls))
Dog.set("speak", lambda self: f"{self.get('name')} barks.")
a = Animal.call_colon("new", None, "Generic Animal")
d = Dog.call_colon("new", None, "Buddy", "Golden Retriever")
Person = ProtoObject()
Person.set("new", lambda cls, name="", age=0: ProtoObject({"name": name, "age": age}, proto=cls))
Person.set("greet", lambda self: f"Hello, my name is {self.get('name')}")
Student = Person.call_colon("new")
Student.set("greet", lambda self: f"Hi, I'm a student and my name is {self.get('name')}")
p2 = Person.call_colon("new", "Charlie", 25)
s2 = Student.call_colon("new", "David", 18)
expected = {
"animal_speak": "Generic Animal makes a sound.",
"dog_override_speak": "Buddy barks.",
"poly_person": "Hello, my name is Charlie",
"poly_student": "Hi, I'm a student and my name is David",
}
actual = {
"animal_speak": a.call_colon("speak"),
"dog_override_speak": d.call_colon("speak"),
"poly_person": p2.call_colon("greet"),
"poly_student": s2.call_colon("greet"),
}
return {
"name": "method_override_and_polymorphism",
"summary": "校验子类重写父类方法(Animal/Dog)与同名接口多态动态派发(Person/Student)",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def case_encapsulation_and_abstraction():
def new_encapsulated_person(name, age):
state = {"name": name, "age": age} # closure-private state
return {
"getName": lambda: state["name"],
"setName": lambda v: state.__setitem__("name", v),
"showInfo": lambda: [f"Name: {state['name']}", f"Age: {state['age']}"],
}
obj = new_encapsulated_person("Alice", 28)
obj["setName"]("Alicia")
expected = {
"private_field_hidden": True,
"name_via_getter": "Alicia",
"abstract_info": ["Name: Alicia", "Age: 28"],
}
actual = {
"private_field_hidden": "name" not in obj,
"name_via_getter": obj["getName"](),
"abstract_info": obj["showInfo"](),
}
return {
"name": "encapsulation_and_abstraction",
"summary": "校验通过 getter/setter 与闭包状态隐藏内部字段(封装)并暴露 showInfo 统一接口(抽象)",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def main():
cases = [
case_prototype_class_and_colon_sugar(),
case_rectangle_and_square_inheritance(),
case_method_override_and_polymorphism(),
case_encapsulation_and_abstraction(),
]
print(json.dumps({"version": VERSION, "cases": cases}, ensure_ascii=False, indent=2))
if __name__ == "__main__":
main()
- 离线脚本确认 Person 冒号与点号传 self 等价、Square 复用 Rectangle:printArea 输出 16、Animal/Dog 重写与 Person/Student 多态派发以及闭包私有字段隐藏。
所需环境:Windows x64、CPython 3.12.14 离线 Lua 5.4 语义验证器(本机未安装原生 lua/luac 解释器)。
当前源码 SHA256:ec126d7a5f9d700aa37c7eea1d07c3d2192d878f8e7d576265518dd5136dcaaf
本地运行
解压后按 README 说明在对应本地环境运行脚本。
所需环境:Windows x64、CPython 3.12.14 离线 Lua 5.4 语义验证器(本机未安装原生 lua/luac 解释器)。
ZIP SHA256:f5be6c330c016dfa0b2ce2a36252e427f73de275c30cf3a3c1fd5bf4cb76235f
常见错误与边界
- 实际端口、文档资源与应用配置都应和测试条件一致。
练习与解答
在 Lua 面向对象写法中,`r:printArea()` 与 `r.printArea()` 有什么本质区别?如果不小心把冒号写成了点号会发生什么?
展开参考解答
`r:printArea()` 会自动把 `r` 作为第一个隐式参数 `self` 传入(等价于 `r.printArea(r)`);若误写成 `r.printArea()`,`self` 会变为 `nil`,在方法体内访问 `self.area` 时立即触发索引 `nil` 值的运行时错误。