How to Call a Lua function from C?

LuaServer Side ProgrammingProgramming

Calling a Lua function from C is something that requires a series of steps and a mastery in the Lua library functions. Lua provides several library functions that we can use whenever we want to call Lua functions from C or the opposite.

Some of the most commonly used Lua library functions for calling a Lua function from C are −

  • luaL_dofile(L, "myFile.lua");
  • lua_getglobal(L, "add");
  • lua_pushnumber(L, a);

and much more.

We will make use of these functions when we will call a Lua function from C.

The first step is to shut down the Lua interpreter and for that we need to write a code in C.


Consider the example shown below −

extern "C" {
   #include "lua.h"
   #include "lualib.h"
   #include "lauxlib.h"
int main(int argc, char *argv[]) {
   lua_State* L;
   L = luaL_newstate();
   printf( "Press enter to exit..." );
   return 0;

Now, we just need to call the luaL_dofile(L, "myFile.lua"); function for the file in which we will write some Lua code that will get invoked from the C code.

Consider the code shown below as written inside the myFile.lua −

add = function(a,b)
return a + b

Now the C file which will call the above Lua function will look something like this −

int luaAdd(lua_State* L, int a, int b) {
   // Push the add function on the top of the lua stack
   lua_getglobal(L, "add");
   // Push the first argument on the top of the lua stack
   lua_pushnumber(L, a);
   // Push the second argument on the top of the lua stack
   lua_pushnumber(L, b);
   // Call the function with 2 arguments, returning 1 result
   lua_call(L, 2, 1);
   // Get the result
   int sum = (int)lua_tointeger(L, -1);
   lua_pop(L, 1);
   return sum;

And when we call this luaAdd() function in C, the output will be:(for a = 2,b = 3)

Published on 20-Jul-2021 14:15:23