lua-users home
lua-l archive

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


On Tue, 15 Jul 2008 11:19:10 +0200 (MESZ)
Michael Gerbracht <smartmails@arcor.de> wrote:

> function call(f,n)
>   x = 5
>   y = loadstring("return "..f)
>   z = y()
>   print(z)
> end
> 
> call("add(n)",12)

Your function doesn't make use of the n parameter, which explains why
the 12 isn't having any effect.

I'm going to assume your use of globals is intentional, rather than
lack of style :) but try this;

x = 5

function add(m)
  x = x + m
  return x
end

function call(func, ...)
  local f = _G[func] or error("unknown function called: " .. func)
  local z = f(...)

  print(z)
end

call("add", 12)

Here, that prints "17".

There are perhaps more elegant solutions to this: it assumes the
function is in the globals table.  Perhaps put your callable functions
in their own table and look them up in that?

(I'm assuming you're receiving the "add" string from the user, and thus
can't just do 'add(12)').

B.