zoukankan      html  css  js  c++  java
  • Lua函数声明与调用

    lua编程中,我们经常也会遇到函数的声明定义和调用。

    【1】lua中函数定义与调用的方法

    lua有两种函数定义和调用的方法(本质都是用属性,方式不同而已):

    (1)点号形式

    (2)冒号形式

    两种方法的联系:

    (1)相同点:本质都是用属性方式

    (2)不同点:用冒号形式定义的函数默认会有一个参数self。self实质指向表本身(类似于C++中的this)。

    【2】两种方法的定义调用实例对比

    综上可知,两种方式会有四种组合需求:

    (1)点号定义 && 点号访问

    _M = {value = 10}
    
    function _M.set_value(_M, new_value)
        _M.value = new_value
    end
    
    function _M.print_sum(_M)
        print(_M.value + _M.value)
    end
    
    print(_M.value)
    _M.set_value(_M, 20)
    print(_M.value)
    _M.print_sum(_M)
    
    --[[
    10
    20
    40
    --]]

    (2)冒号定义 && 冒号访问

    _M = {value = 10}
    
    function _M:set_value(new_value)
        self.value = new_value
    end
    
    function _M:print_sum()
        print(self.value + self.value)
    end
    
    print(_M.value)
    _M:set_value(20)
    print(_M.value)
    _M:print_sum()
    
    --[[
    10
    20
    40
    --]]

    (3)点号定义 && 冒号访问

    _M = {value = 10}
    
    function _M.set_value(_M, new_value)
        _M.value = new_value
    end
    
    function _M.print_sum(_M)
        print(_M.value + _M.value)
    end
    
    print(_M.value)
    _M:set_value(20)
    print(_M.value)
    _M:print_sum()
    
    --[[
    10
    20
    40
    --]]

     (4)冒号定义 && 点号访问

    _M = {value = 10}
    
    function _M:set_value(new_value)
        self.value = new_value
    end
    
    function _M:print_sum()
        print(self.value + self.value)
    end
    
    print(_M.value)
    _M.set_value(_M, 20)
    print(_M.value)
    _M.print_sum(_M)
    
    --[[
    10
    20
    40
    --]]

    Good Good Study, Day Day Up.

    顺序 选择 循环 总结

  • 相关阅读:
    【科普杂谈】计算机按下电源后发生了什么
    【VS开发】使用WinPcap编程(1)——获取网络设备信息
    【VS开发】使用WinPcap编程(1)——获取网络设备信息
    微信公众平台消息接口PHP版
    编码gbk ajax的提交
    mysql 查询
    js cookie
    js同域名下不同文件下使用coookie
    去掉A标签的虚线框
    jquery切换class
  • 原文地址:https://www.cnblogs.com/Braveliu/p/11265413.html
Copyright © 2011-2022 走看看