表可以使用:
或者.
来声明/调用函数。二者在用法上区别如下:
- 声明的时候使用
:
,隐含了一个形参self的声明。.
则没有
function tab:fun1()
--do something
end
--等价于
function tab.fun1(self)
--do something
end
-
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()