lua-users home
lua-l archive

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


On 06/10/14 13:50, Charles Smith wrote:
> I need to take the time to develop a clearer example, but I think the
> point is, alt1 and alt2 also use msg_union.  That's what I mean by
> recursive design.  It's a classic chicken/egg issue.
> 
> On Mon, Oct 6, 2014 at 2:35 PM, Coda Highland <chighland@gmail.com
> <mailto:chighland@gmail.com>> wrote:
> 
>     On Mon, Oct 6, 2014 at 5:30 AM, Charles Smith
>     <cts.private.yahoo@gmail.com <mailto:cts.private.yahoo@gmail.com>>
>     wrote:
>     > Recursive design.
>     >
>     >
>     > msg_union = {
>     >   ["0"] = "alt1",
>     >   ["1"] = "alt2",
>     >   ...
>     > }
>     >
>     > function alt1 (body)
>     > ...
>     > function alt2 (body)
>     >
>     >
>     > ielen = _G[msg_union[tostring (selector)]] (buffer(offset), pinfo, tree)
>     >
>     > Maybe there's a better way?  It looks like it's going to be slow.
>     >
>     >
>     > The msg_union has to be defined before it can be used by the (sub)msgs.  But
>     > it needs access to the (sub)msgs.


-- value from somewhere
v = 1

-- pre-define a local table
local msg_union = {}

-- fill the local with a table of functions that can refer to itself
msg_union[1] = function()
  print("mu:1")
  msg_union[2]()
end

msg_union[2] = function()
  print("mu:2")
  msg_union[3]()
end

msg_union[3] = function()
  print("mu:3)
end

-- call based on value
msg_union[v]()


There's also the ':' syntactic sugar that allows you to call a function
in a table and pass the table as the first argument.

local tab = {
  f1 = function(self, val)  -- 'self' argument manually specified
    print("In f1")
    print("tab.v =", self.v)
    print("val =", val)
  end,

  v = 123,
}

function tab:f2(val)  -- 'self' argument is created here for you
  print("In f2")      --   with the ':' operator
  self:f1(val)
end,

tab.f1(tab, "test1")  -- manually passing the table

tab:f1("test2")  -- automatically passing it with the ':'
tab:f2("test3")  --   operator

Bottom line, avoid globals where possible, pass info via arguments.

Scott