Lua Introduction to Lua C API Embedded Lua Interpreter with Custom API and Lua Customization

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

Demonstrate how to embed a lua interpreter in C code, expose a C-defined function to Lua script, evaluate a Lua script, call a C-defined function from Lua, and call a Lua-defined function from C (the host).

In this example, we want the mood to be set by a Lua script. Here is mood.lua:

-- Get version information from host
major, minor, build = hostgetversion()
print( "The host version is ", major, minor, build)
print("The Lua interpreter version is ", _VERSION)

-- Define a function for host to call
function mood( b )

    -- return a mood conditional on parameter
    if (b and major > 0) then
        return 'mood-happy'
    elseif (major == 0) then
        return 'mood-confused'
    else
        return 'mood-sad'
    end
end

Notice, mood() is not called in the script. It is just defined for the host application to call. Also notice that the script calls a function called hostgetversion() that is not defined in the script.

Next, we define a host application that uses 'mood.lua'. Here is the 'hostlua.c':

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

/* 
 * define a function that returns version information to lua scripts
 */
static int hostgetversion(lua_State *l)
{
    /* Push the return values */
    lua_pushnumber(l, 0);
    lua_pushnumber(l, 99);
    lua_pushnumber(l, 32);

    /* Return the count of return values */
    return 3;
}

int main (void)
{
    lua_State *l = luaL_newstate();
    luaL_openlibs(l);

    /* register host API for script */
    lua_register(l, "hostgetversion", hostgetversion);

    /* load script */
    luaL_dofile(l, "mood.lua");

    /* call mood() provided by script */
    lua_getglobal(l, "mood");
    lua_pushboolean(l, 1);
    lua_call(l, 1, 1);

    /* print the mood */
    printf("The mood is %s\n", lua_tostring(l, -1));
    lua_pop(l, 1);

    lua_close(l);
    return 0;
}

And here is the output:

The host version is     0    99    32
Lua interpreter version is     Lua 5.2
The mood is mood-confused

Even after we have compile 'hostlua.c', we are still free to modify 'mood.lua' to change the output of our program!



Got any Lua Question?