Skip to main content
gamedev.net
🔒 Locked

[C++/Lua] About call Lua function by function name string

Started by shawnee May 21, 2009 at 11:40 PM 1 replies 5.8k views
Original Post
shawnee
shawnee
Hi All, I got a string from C++ code in Lua script. This string is the name of a Lua function in this Lua script file. I received this string and just use this string and plus "()" to execute, but nothing happen. It seems this method causes to function is not "alive". How can I execute Lua function by string? Anybody could help me? Thanks a lot! example Lua script: function a() print("a") end fname = getLuaFunctionNamefromC() -- fname is "a" fname() -- is equivalent to call a(), -- but nothing happened!
ddn3
ddn3
You can do something like this, if u have a mapping of string name -> function in a particular table u like to use.

Like so:

local allFunc={}allFunc["a"]=a;fname = getLuaFunctionNamefromC();if (allFunc[fname]~=nil) then allFunc[fname](); end


Or if not something like this, which will execute the compiled string.

fname = getLuaFunctionNamefromC();--this makes a executable Lua snippet which calls ur function by its real name.local str = ""..fname.."();";loadstring(str);



Or if you made the function global you can use the global table like so:

fname = getLuaFunctionNamefromC();if (_G[fname]~=nil) then _G[fname ]() end;



Be aware if your going to use the global table, that what your calling actually a function ( u can check the type if u wish ).

Good Luck!

-ddn
shawnee
shawnee
the first way is nice!
thank you, ddn. :-)

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.