If you have a string that could be the name of a global function:
local func = "print" if _G[func] then _G[func]("Test") -- same as: print("test") end
and if you have a function that can be valid:
local func = print if func then func("ABC") -- same as: print("ABC") end
If you are interested in what is happening and what the background is above, _G is a global table in lua, in which each global function is stored. This table stores global variables by name as a key, as well as a value (function, number, string). If your table _G does not contain the name of the object you are looking for, then your object may not be an existing or local object.
In the second field of code, we create a local variable called func and assign it the value print as the value. (Note that there is no need for brackets. If you open the brackets, it calls the function and gets the output value, not the it self function).
the if on the block checks if your function exists or not. In a lua script, not only booleans can be checked using a simple if , but functions and the existence of objects can be checked using a simple if .
Inside our if block, we call our local variable, just as we call the global value function ( print ). This is more like giving our print function a print name or short name for ease of use.
source share