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

简介: ----------------------------------------------------------- Lua面向对象3local smartMan = { name = "Tinywan", age = 26, money = 800000, ...

----------------------------------------------------------- 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 返回

 

目录
打赏
0
0
0
0
27
分享
相关文章
|
10月前
lua面向对象(类)和lua协同线程与协同函数、Lua文件I/O
Lua的面向对象编程、协同线程与协同函数的概念和使用,以及Lua文件I/O操作的基本方法。
124 4
lua面向对象(类)和lua协同线程与协同函数、Lua文件I/O
【Lua】《Lua 程序设计》摘录
【Lua】《Lua 程序设计》摘录
187 3
AI助理

你好,我是AI助理

可以解答问题、推荐解决方案等

登录插画

登录以查看您的控制台资源

管理云资源
状态一览
快捷访问