Lua 的 私有性

来源:互联网 发布:java float 0 比较 编辑:程序博客网 时间:2024/04/29 14:51
今天在写背包类时,如果是C++的话,背包里面的道具无疑应该是背包类私有的,背包类应该提供对道具的增删查操作,而避免外部直接访问道具数据,所以想到用Lua实现对道具的封装。但是事与愿违。Lua 是通过闭包来实现私有的,如下:
function newAccount (initialBalance)        local self = { balance = initialBalance ,                          LIM = 1314 }        local withdraw = function (v)            self.balance = self.balance - v        end          local extra = function ()            if self.balance > self.LIM then                return self.balance*0.10            else                return 0            end         end         local deposit = function (v)            self.balance = self.balance + v         end         local getBalance = function ()                 return self.balance + extra()  --[此处非self.extra()]         end         return {            withdraw = withdraw,            deposit = deposit,            getBalance = getBalance,            -- extra = extra,        } end

如果一定要实现私有性,就要放弃Lua的继承(self)性,我选择放弃,转而使用折衷的办法来处理数据的私密性,就是学习quick的代码风格,将私有的变量和方法用命名后加下划线表示。

0 0