Lua Calling Lua functions


#include <stdlib.h>

#include <lauxlib.h>
#include <lua.h>
#include <lualib.h>

int main(void)
    lua_State *lvm_hnd = lua_open();

    /* Load a standard Lua function from global table: */
    lua_getglobal(lvm_hnd, "print");

    /* Push an argument onto Lua C API stack: */
    lua_pushstring(lvm_hnd, "Hello C API!");

    /* Call Lua function with 1 argument and 0 results: */
    lua_call(lvm_hnd, 1, 0);


    return EXIT_SUCCESS;

In the example above we're doing these things:

  • creating and setting up Lua VM as shown on the first example
  • getting and pushing a Lua function from global Lua table onto virtual stack
  • pushing string "Hello C API" as an input argument onto the virtual stack
  • instructing VM to call a function with one argument which is already on the stack
  • closing and cleaning up


Bare in mind, that lua_call() pops the function and it's arguments from the stack leaving only the result.

Also, it would be safer using Lua protected call - lua_pcall() instead.