lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


On Sep 11, 2014 11:09 AM, "albert_200200" <albert_200200@126.com> wrote:
>
> First I use the following code to define a lua class:
> clsSMSSend = {}
> function clsSMSSend:new()
>     local o = {}
>     setmetatable(o, self)
>     self.__index = self
>     o.MobileNo            = "oldmobile"
>     o.tbl_body  = {
>         [1]     = o.MobileNo,
>     }
>     return o
> end
>
> The problem is as below:
> obj = clsSMSSend:new()
> obj.MobileNo = "newmobile"
> for k, v in ipairs(obj.tbl_body) do
>     print(k, v) --but here still print "oldmobile" not "newmobile"
> end
>
> If I want the code to print "newmobile", how can I correct it? Thanks.

The problem here is that you set MobileNo as a value in tbl_body, i.e. a copy of a string. And you are modifying only one value - strings are not refs. You need to implement __newindex metamethod in o to keep your two structures in sync or __index metamethod in tbl_body to actually return o.MobileNo when index 1 is requested.