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


     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

     

  • 相关阅读:
    jquery实现章节目录效果
    Delphi里如何让程序锁定在桌面上,win+d都无法最小化
    php 之跨域上传图片
    delphi判断文件类型
    EmptyRecycle() 清空回收站
    delphi检查url是否有效的方法
    Explode TArray
    css设置中文字体(font-family:"黑体")后样式失效问题
    javascript-lessons
    课后作业2
  • 原文地址:https://www.cnblogs.com/tinywan/p/6950088.html
Copyright © 2020-2023  润新知