lua-users home
lua-l archive

Re: how to make two different function(object?) share a private value?

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


A while long I made a function returning two interfaces, the usual for
the object and another special access access.
function createObject()
 local t = {}
 local sa = {}
 local i = i or 5
 function t:Foo()
 print("foo, i = ", i)
 end
 function sa:getI()
 return i
 end
 return t, sa
end
So whereever you create it, you get two handels
o, sa = createObject
and pass the normal away and keep the special interface
If you have to get special access from normal object only, you can
make a table for that.
local oToSa = {}
setmetatable(oToSa, __mode = "k")
function createObject()
 local t = {}
 local sa = {}
 local i = i or 5
 function t:Foo()
 print("foo, i = ", i)
 end
 function sa:getI()
 return i
 end
 oToSa[o] = sa
 return t, sa
end
now whoever has access to oToSa can get the special interface from the object,
setmetatable(oToSa, __mode = "k")
Advices the garbage collector to delete the entry in the table if the
object is no longer used.
On Tue, Dec 7, 2010 at 2:33 AM, starwing <weasley.wx@gmail.com> wrote:
> hi, everyone :-)
> now I made a OO style with lua, use a table of closure:
> function object(i)
>     local t = {}
>     local i = i or 5
>     function t:Foo()
>         print("foo, i = ", i)
>     end
>     return t
> end
> now "i" is a true private data member in class object. only function Foo can
> "see" what i is,
> but, when i use this tech to implement a control-contianer complement
> system, I have to put member data to the table: because I must let Control
> object and Container object all access the member data! in C++, we can do it
> with friend class, but I can not do this in lua:
> function Control(parent)
>     local t = {}
>     ....
>     local has_focus
>     function t:SetFocus(focus)...end
>     function t:HasFocus() return has_focus end
>
>    ...
>    return t
> end
> function Container(parent)
>     local t = Control(parent) -- Container is-a Control
>     local focus_child
>     function t:SetFocusChild(child)...end
>     function t:GetFocusChild() return focus_child end
>     ...
>     return t
> end
>
> Control().SetFocus can change the value of "has_focus", but SetFocusChild
> can't do that, it must use something to change the value of has_focus, and
> this thing must not call by user himself. (because these function e.g.
> SetRawFocus can not change "focus_child" value in Container, so it will
> break data), or I could put has_focus to public area(i.e. put it in table),
> but in this scene, anybody can change its value.
> i just want a function SetFocus can change the value of focus_child, and a
> function SetFocusChild can change the value of has_focus. i.e. these two
> closure-variable are shared by two linked object.
> has anybody have good idea to do this?

AltStyle によって変換されたページ (->オリジナル) /