Lua 模仿C++类

Lua类的声明与定义

在文件中"AInfoClass.lua"声明并定义一个Lua类。

Lua 复制代码
local AInfoClass = {}

function AInfoClass.New(id)
    local tempTab = {}
    tempTab.id = id

    setmetatable(tempTab, {__index = AInfoClass})

    tempTab:InitClass()
  
    return tempTab
end

function AInfoClass:InitClass()
    self.name = tostring(self.id .."_Name")
    self.val = self:GetValue()
end

function  AInfoClass:GetValue()
    return 199
end

function AInfoClass:PrintInfo()
    local str = string.format("id=%s,name=%s,val=%s", self.id, self.name,self.val)
    print(str)
end

return AInfoClass

Lua 类的使用

在新的文件中"ATestClass.lua"声明定义一个Lua类对象

Lua 复制代码
local AInfoClass = require("AInfoClass")

local info = AInfoClass.New(1899)
info:PrintInfo()

---判断info.PrintInfo2 是否存在
if info.PrintInfo2 then
    print("info.PrintInfo2 exist !!")
else
    print("info.PrintInfo2 not exist !!")
end

输出运行结果

Lua 复制代码
id=1899,name=1899_Name,val=199
info.PrintInfo2 not exist !!
相关推荐
Hy行者勇哥2 小时前
Python 与 VS Code 结合操作指南
开发语言·python
麦兜*8 小时前
Swift + Xcode 开发环境搭建终极指南
开发语言·ios·swiftui·xcode·swift·苹果vision pro·swift5.6.3
萧鼎9 小时前
Python pyzmq 库详解:从入门到高性能分布式通信
开发语言·分布式·python
艾伦~耶格尔10 小时前
【集合框架LinkedList底层添加元素机制】
java·开发语言·学习·面试
yujkss10 小时前
Python脚本每天爬取微博热搜-终版
开发语言·python
yzx99101310 小时前
小程序开发APP
开发语言·人工智能·python·yolo
啊阿狸不会拉杆10 小时前
《算法导论》第 32 章 - 字符串匹配
开发语言·c++·算法
武当豆豆12 小时前
C++编程学习(第25天)
开发语言·c++·学习
-Xie-14 小时前
Maven(二)
java·开发语言·maven
mftang14 小时前
Python可视化工具-Bokeh:动态显示数据
开发语言·python