Lua程序设计(三)面向对象实现一个简单的类

简介: 1.Lua面向对象实现步骤①创建一个全局表(称之为元表)②设置这个元表的__index值(值通常为元表自己,这样就能通过__index查找到对应的属性和方法)__index 赋值其实是一个function的语法糖,Sharp.

 1.Lua面向对象实现步骤

①创建一个全局表(称之为元表)

②设置这个元表的__index值(值通常为元表自己,这样就能通过__index查找到对应的属性和方法)__index 赋值其实是一个function的语法糖,Sharp.__index = Sharp等价于Sharp.__index = function(key) return Sharp[key] end 

 

③新建一个表,使用setmetatable方法将元表设置到这个新表中,那这个新表就能以对象的方式来调用对应的属性和方法了,当这个对象调用属性或者函数时,首先查找自身的元表,如果找到则返回;如果没找到,则检查元表中是否有__index,如果有,则使用__index的值继续查找,直到没有__index为止。

2.例子

①代码 

Sharp = { _val = 1}  --①  父类

function Sharp:new()
    local new_sharp = { }
    self.__index = self  --②,self == Sharp
    setmetatable(new_sharp, self)  --return new_sharp
end

function Sharp:sharp_func()
    print("Sharp call sharp_func")
end

function Sharp:name()
    print("Sharp call name")
end

function Sharp:val()
    print(string.format("Sharp call val %d", self._val))
end

②调用代码

local sharp = Sharp:new()
sharp:sharp_func()
sharp:name()
sharp:val()

 ③输出结果

 

3.自己写一个类

class1.lua

local ok, new_tab = pcall(require, "table.new")
if not ok or type(new_tab) ~= "function" then
    new_tab = function (narr, nrec) return {} end
end

local _M = new_tab(0, 54)       --①  父类

_M._VERSION = '0.01'

function _M:new()
    local new_obj = {}
    self.__index = self          --②,self == _M
    setmetatable(new_obj, self)
    return new_obj
end

-- 定义个简单的方法
function _M:func()
    print("Function func ")
end

return _M

简单的调用

local class01 = require "class1"
print("_VERSION == "..class01._VERSION)
local func = class01:func()
print(func)

打印结果

_VERSION == 0.01
Function func 
nil

 

目录
相关文章
|
3月前
|
C++ 索引 Python
Lua中self 、自索引及其面向对象应用代码示例
Lua中self 、自索引及其面向对象应用代码示例
|
11月前
Lua面向对象
Lua面向对象
60 0
|
数据采集 Linux C++
【Lua】《Lua 程序设计》摘录
【Lua】《Lua 程序设计》摘录
88 3
|
API C语言 索引