lua-users home
lua-l archive

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


Abhinav Lele writes:
> Hi,Suppose i known the string name of a function that I
> have in my script.How can i call that function, knowing
> only the stringname of the function.

If the functions are stored in global variables as follows:

  function double(x) print(x*2) end
  function triple(x) print(x*3) end

then you can access them by name through the _G table:

  local name = "double"
  _G[name](10)

More generally, they are available through the current environment table
obtained by calling getfenv():

  getfenv()[name](10)

You might alternately store and use the functions in your own table as such:

  local funcs = {}
  function funcs.double(x) print(x*2) end
  function funcs.triple(x) print(x*3) end
  local name = "double"
  funcs[name](10)

The common thread in all these approaches is that the functions are stored in a
table.