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 !!
相关推荐
secret_to_me几秒前
裴行俭VS袁天罡和李淳风
开发语言
2601_953465611 分钟前
M3U8 在线播放器:无需安装,一键调试 HLS 直播流
开发语言·前端·javascript·开发工具·m3u8·m3u8在线播放
郭涤生9 分钟前
C++ 线程同步复习
开发语言·c++
Full Stack Developme11 分钟前
Hutool EnumUtil 教程
开发语言·windows·python
XMYX-013 分钟前
18 - Go 等待协程:WaitGroup 使用与坑
开发语言·golang
feifeigo12316 分钟前
基于遗传算法的矩形排样MATLAB实现
开发语言·matlab
他是龙55120 分钟前
65:JS安全&浏览器插件&工具箱等
开发语言·javascript·安全
csbysj202020 分钟前
Rust 输出到命令行
开发语言
likerhood24 分钟前
Java 中的 `clone()` 与 `Cloneable` 接口详解
java·开发语言·python
Adellle29 分钟前
Java 异步回调
java·开发语言·多线程