Skip to content
This repository was archived by the owner on Dec 11, 2025. It is now read-only.
This repository was archived by the owner on Dec 11, 2025. It is now read-only.

How do I configure laura be used with custom C/C++ extensions? #3

@MichaelBonnet

Description

@MichaelBonnet

Say I had something like this main.c:

#include <stdio.h>
#include <stdlib.h>
#include "lua5.4/lua.h"
#include "lua5.4/lauxlib.h"
#include "lua5.4/lualib.h"

// compile : gcc main.c -o custom_lua_app -I/usr/include/lua5.4 -llua5.4 -lm -ldl
// run     : ./custom_lua_app script1.lua

/**
 * sumLua: Expects two numbers on the stack; returns their sum.
 * Stack layout (top at the right):
 *   1: number
 *   2: number
 */
static int sumLua(lua_State* L) {
    // Check we have 2 arguments
    int nArgs = lua_gettop(L);
    if(nArgs != 2) {
        return luaL_error(L, "sumLua expects exactly 2 arguments!");
    }

    // Get arguments (both should be numbers)
    if(!lua_isnumber(L, 1) || !lua_isnumber(L, 2)) {
        return luaL_error(L, "sumLua expects numbers!");
    }

    double a = lua_tonumber(L, 1);
    double b = lua_tonumber(L, 2);

    // Compute sum
    double result = a + b;

    // Push result onto the Lua stack
    lua_pushnumber(L, result);

    // Return 1 value to Lua
    return 1;
}

int main(int argc, char** argv) {
    // Create Lua state
    lua_State* L = luaL_newstate();

    // Open standard libraries
    luaL_openlibs(L);

    // Register functions
    lua_register(L, "sumLua", sumLua);

    // Check if the user passed a script name
    if(argc < 2) {
        printf("Usage: %s <Lua script>\n", argv[0]);
        lua_close(L);
        return 1;
    }

    // Load and run the Lua script
    if(luaL_loadfile(L, argv[1]) || lua_pcall(L, 0, 0, 0)) {
        fprintf(stderr, "Error: %s\n", lua_tostring(L, -1));
        // lua_pop(L, 1); // remove error message
        lua_close(L);
        return 1;
    }

    // Clean up and close Lua
    lua_close(L);
    return 0;
}

with script1.lua:

-- script1.lua

-- Call sumLua, which is defined in C
local x = 10
local y = 25
local s = sumLua(x, y)
print("Lua: The sum of ", x, " and ", y, " is ", s)

How might I configure Laura such that I can unit test the Lua use of available custom C functions?

Metadata

Metadata

Assignees

No one assigned

    Labels

    questionFurther information is requested

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions