1

I have a function e.g.

function run()
    print("hi")
end

I have a string called message which contains the word "run":

activity = message
print(activity) --returns run

However I am unable to use the string activity to run the function run(). I have tried:

func = loadstring(activity.."()")
func() -- I get an error on line 1 saying: attempt to call nil
warspyking
  • 3,045
  • 4
  • 20
  • 37
  • 1
    Can you put those (partial) snippets of code into context with each other? Where is `run` in relation to `activity` in the code? – Etan Reisner Jul 02 '15 at 20:47
  • 1
    Also `_G[activity]()` is more efficient than `loadstring(activity.."()")()` – Colonel Thirty Two Jul 02 '15 at 20:50
  • Functions (like all values) don't have names. Variables have names. It would be more correct to say that you have a global variable that references a function and you want to call the function using the name of the variable in a string. – Tom Blodget Jul 02 '15 at 23:17

2 Answers2

2

Well, the function run is stored in _G so the simple answer:

_G[message]()
warspyking
  • 3,045
  • 4
  • 20
  • 37
1
function run() print("hi") end
activity = "run"
loadstring(activity.."()")()

This works fine as long as loadstring is running in the same environment as run. In other words, the loadstring line is equivalent to _G[activity](). If the global run was created in some other environment, that'll evaluate to nil.

Given that Lua functions are first class values, just like strings, if at all possible it would be better to do this:

function run() print("hi") end
activity = run
activity()

Though if this is in a context where you're getting a string value from config file or something, that wouldn't work.

Mud
  • 28,277
  • 11
  • 59
  • 92