lua-users home
lua-l archive

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


On Wed, Feb 25, 2009 at 11:38 AM, Luis F Urrea <lfurrea@gmail.com> wrote:
> Our team is learning the subtleties of LUA and we are on a small newbies
> debate.
>
> We are wondering what would be cheaper between calling a function from a
> table lookup or a string matching function.

"cheaper" as in "faster"?

Benchmark it! If you can't tell the difference in the bm, then make it
as readable as possible.

> Basically we have a Table that stores the name of the function. When a state
> machine runs and returns the name of the function we have the option to do
> this:

The overhead of an
  if a == "this" then
  elseif b == "that"
 elseif ..

is linear in the number of conditions, so will get worse and worse as
you add conditions.

The overhead of a table lookup "might" be higher than a single
comparison, but should increase much less than linearly as the table
size grows.

> local actions = { pAuthRequest =  function ()
>                                          print("Auth request coming!")
>                                       end,
>                       ClientSend =  function ()
>                                        master:send(auth_string)
>                                     end,
>                       pCommandReply =  function ()
>                                           print("Woohooo")
>                                        end,
>                       pWaiting = function ()
>                                     print("Waiting for more")
>                                  end,
>                    }
>
> local action = actions[a.action]
>          action()

Or

({
   a = ...,
   b = ...,
})[a.action]()

Sam