Lua Introduction to Lua C API Calling Lua functions

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Insert
> Step 2: And Like the video. BONUS: You can also share it!

Example

#include <stdlib.h>

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

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

    /* 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);

    lua_close(lvm_hnd);

    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

NOTE:

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.



Got any Lua Question?