So I'm working on a game and I want to use a string that can be called as a function so I can quickly call multiple functions all at once. I have an example of something I'm trying to get work:
function state_machine_1()
print("Hello world")
end
function state_machine_2()
print("Goodbye world")
end
local func="state_machine_".."1"
load(func)()
func="state_machine_".."2"
load(func)()
When I run the code in the lua demo site I get the exact same error now which is "attempt to call a nil value". I've tried looking it up but load() is too vague for search engines to know even with context. Any ideas of what I can change?
The nil error happens because it fails to compile the code
You can add an assert to catch the compile error
assert(load(func))()
The reason it fails because func
should end with ()
for it to be a function call.
local func = "state_machine_" .. "1" .. "()"
assert(load(func))()