How to Check if a Lua Function Exists


Lua language logo

Almost every new version of GeeXLab brings some new functions in the Lua scripting API. So it can be useful to know if a function is exposed by a particular version of GeeXLab in order to avoid crashes if your demo runs with an older version of GeeXLab.

In Lua, all functions are referenced by a global variable called _G (actually, Lua stores the environment itself in the global variable _G). So if you define a new function in a Lua script like this one:

function test_func1()
  return "Hello!"
end

You can check its presence using _G:

if (_G["test_func1"] ~= nil) then
  print("test_func1 is exposed") 
end

To check whether a GeeXLab function is exposed or not, you have to do a two-step test:
1/ check the presence of the library
2/ check the function name in this library

Let’s see an example with the gh_utils.get_demo_dir() function:

if (_G['gh_utils'] ~= nil) then
  print("gh_utils lib is exposed") 
 
  if _G['gh_utils']['get_demo_dir'] ~= nil then 
    print("gh_utils.get_demo_dir() is exposed") 
  else
    print("gh_utils.get_demo_dir() is NOT exposed") 
  end
else
    print("gh_utils lib is NOT exposed") 
end


Leave a Comment

Your email address will not be published. Required fields are marked *