【lua】lua表中函数:和.区别

表可以使用:或者.来声明/调用函数。二者在用法上区别如下:

  1. 声明的时候使用:,隐含了一个形参self的声明。.则没有
function tab:fun1()
	--do something
end
--等价于
function tab.fun1(self)
	--do something
end
  1. 1) 调用的时候,:将调用者作为第一个参数传给函数。.则不会
    在使用:调用函数的时候需要注意,如果函数声明的时候不是用:声明,则声明处第一个参数必须是self否则会出错:

    tab = {
    name = "ming"
    }
    
    function tab.print_parameter(a)
        print("the parameter is ")
        print(a)
    end
    
    tab:print_parameter("a parameter")
    

    我们期望它的输出是: the parameter is a parameter
    实际的输出是:
    在这里插入图片描述
    原因就在于,函数调用的时候tab:print_parameter("a parameter")这里使用了:调用了函数

    2) 调用函数的时候使用.可以传入其它的table。利用这种方式借用其它表的函数,实现多继承

    tab.fun1(othertable)
    

如下四个程序效果是等价的:

stu = {
    name = "ming"
}

function stu:hello()
    print("hello world")
    print("My name is " .. self.name)
end

stu:hello()
stu = {
    name = "ming"
}

function stu.hello(self)
    print("hello world")
    print("My name is " .. self.name)
end

stu.hello(stu)
stu = {
    name = "ming"
}

function stu:hello()
    print("hello world")
    print("My name is " .. self.name)
end

stu.hello(stu)
stu = {
    name = "ming"
}

function stu.hello(self)
    print("hello world")
    print("My name is " .. self.name)
end

stu:hello()
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值