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 !!
相关推荐
千里镜宵烛1 小时前
深入 Lua 环境机制:全局变量的 “容器” 与 “隔离术”
开发语言·junit·lua
QX_hao6 小时前
【Go】--反射(reflect)的使用
开发语言·后端·golang
inferno6 小时前
Maven基础(二)
java·开发语言·maven
我是李武涯7 小时前
从`std::mutex`到`std::lock_guard`与`std::unique_lock`的演进之路
开发语言·c++
史不了8 小时前
静态交叉编译rust程序
开发语言·后端·rust
读研的武8 小时前
DashGo零基础入门 纯Python的管理系统搭建
开发语言·python
Andy8 小时前
Python基础语法4
开发语言·python
但要及时清醒9 小时前
ArrayList和LinkedList
java·开发语言
孚亭9 小时前
Swift添加字体到项目中
开发语言·ios·swift