Account = {balance = 1000} -- 账户余额初始为1000。
----【定义函数】
--[[ 取钱。
使用面向对象的方式隐藏了"self"参数,
"withdraw()"完整的参数列表是"Account.withdraw(self, v)"。]]
function Account:withdraw(v)
self.balance = self.balance - v
end
----【调用函数】
--[[ 使用面向对象的方式隐藏了"self"参数,
实际传递给"withdraw()"的参数是"Account"和"100.00"。]]
Account:withdraw(100.00)
print(Account.balance) --> 900.0
Account = {balance = 1000} -- 账户余额初始为1000。
function Account.withdraw(self, v) -- 使用"."定义函数。
self.balance = self.balance - v
end
Account:withdraw(100.00) -- 使用":"调用函数。
print(Account.balance) -- 900.0
-- 存钱。
function Account:deposit(v) -- 使用":"定义函数。
self.balance = self.balance + v
end
Account.deposit(Account, 600.00) -- 使用"."调用函数。
print(Account.balance) -- 1500.0
-
总结
用冒号(:)调用函数时,会默认传一个值(调用者自身self)作为第一个参数;
用点(.)调用函数时,则没有
用冒号(:)创建函数时,会默认添加一个参数self,作为第一个参数;
用点(.)调用函数时,则没有
. 和 :函数可以相互调用,但需要正确的传递self值。
]]--