Lua程序设计(二)面向对象概念介绍

本文通过具体示例展示了Lua语言中的面向对象编程技巧,包括metatable的使用、__index和__newindex元方法的功能,并演示了如何为Lua table设置特定的行为。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

----------------------------------------------------------- Lua面向对象3
local smartMan = {
    name = "Tinywan",
    age = 26,
    money = 800000,
    sayHello = function()
        print("Tinywan say 大家好")
    end
}
local t1 = {}
local mt = {
    __index = smartMan,
    __newindex = function(table, key, value)
        print(key .. "字段不存在不要试图给他赋值")
    end
}
setmetatable(t1, mt)
t1.sayHello = function()
    print("HAHA")
end
t1.sayHello()
--- 输出结果
-- sayHello字段不存在不要试图给他赋值
-- Tinywan say 大家好

 

----------------------------------------------------------- Lua面向对象3
local smartMan = {
    name = "none"
}
local other = {
    name = "大家好,我是无赖的table"
}
local t1 = {}
local mt = {
    __index = smartMan,
    __newindex = other
}
setmetatable(t1, mt)
print("other的名字,赋值前:" .. other.name)
t1.name = "峨眉大侠"
print("other的名字,赋值后:" .. other.name)
print("t1 的名字:" .. t1.name)
--- 输出结果
-- other的名字,赋值前:大家好,我是无赖的table
-- other的名字,赋值后:峨眉大侠
-- t1 的名字:none

 

 

 

 

 

有问题

 

 

local 变量不放在全局函数中去

 

以上不需要 return 返回

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值