Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.3k views
in Technique[技术] by (71.8m points)

dynamic - lua call function from a string with function name

Is it possible in lua to execute a function from a string representing its name?
i.e: I have the string x = "foo", is it possible to do x() ?

If yes what is the syntax ?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

To call a function in the global namespace (as mentioned by @THC4k) is easily done, and does not require loadstring().

x='foo'
_G[x]() -- calls foo from the global namespace

You would need to use loadstring() (or walk each table) if the function in another table, such as if x='math.sqrt'.

If loadstring() is used you would want to not only append parenthesis with ellipse (...) to allow for parameters, but also add return to the front.

x='math.sqrt'
print(assert(loadstring('return '..x..'(...)'))(25)) --> 5

or walk the tables:

function findfunction(x)
  assert(type(x) == "string")
  local f=_G
  for v in x:gmatch("[^%.]+") do
    if type(f) ~= "table" then
       return nil, "looking for '"..v.."' expected table, not "..type(f)
    end
    f=f[v]
  end
  if type(f) == "function" then
    return f
  else
    return nil, "expected function, not "..type(f)
  end
end

x='math.sqrt'
print(assert(findfunction(x))(121)) -->11

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...