lua编程中,经常遇到函数的定义和调用。我们有两种函数定义和调用的方法。一种是用属性的方式,另外一种是通过冒号的形式(其实也是属性)。只不过用冒号形式申明的函数默认会有一个参数self。self指向本身(表)。下面举例说明:
shape = {side = 4}
function shape.set_side(shape, side)
shape.side = side
end
function shape.print_area(shape)
print(shape.side * shape.side)
end
print(shape.side)
shape.set_side(shape, 5)
print(shape.side)
shape.print_area(shape)
上述运行结果是:
4
5
25
上面是用“ . ”来定义和访问函数的方法。下面同样用“ :”来实现同样功能的改写如下
shape = {side = 4}
function shape:set_side(side)
self.side = side
end
function shape:print_area()
print(self.side * self.side)
end
print(shape.side)
shape:set_side(5)
print(shape.side)
shape:print_area()
运行结果和上面例子一样:
4
5
25
从上面两个例子我们可以看出:冒号定义和冒号调用其实跟上面的效果一样,只是把第一个隐藏参数省略了。而self则是指向调用者自身。
当然,我们也可以用点号“ . ”来定义函数,冒号“ :”来调用函数。或者冒号定义点号调用。如下:
shape = {side = 4}
function shape.set_side(shape, side)
shape.side = side
end
function shape.print_area(shape)
print(shape.side * shape.side)
end
print(shape.side)
shape:set_side(5)
print(shape.side)
shape:print_area()
或者
shape = {side = 4}
function shape:set_side(side)
self.side = side
end
function shape:print_area()
print(self.side * self.side)
end
print(shape.side)
shape.set_side(shape, 5)
print(shape.side)
shape.print_area(shape)
上述运行结果:
4
5
25
网友评论