'Error loading C++ DLL from Lua in a subdirectory

To give you some context, I am trying to load a C++ DLL from Lua (plain Lua), and it works.. somewhat. If I put the dll file along with my other dependencies' dlls directly in the working directory, it works. But for some organization, I would like to have all of the dlls in another folder inside the working directory. For example, if I have a project named "foo" and I have a subfolder inside that folder called "bar." I have a "scripts" folder in the "foo" folder. Instead of having the DLL in the "foo" folder, I want it in the "bar" folder. My main.lua will be in the "scripts" folder. Here is my main.lua file:

local dll = assert(package.loadlib(".\\bar\\test.dll", "luaopen_test"))()
dll.test()

I am calling the "test" function from the DLL. Here is the main.cpp file:

#include <iostream>
#include <string>

#include "lua/include/lua.hpp"

static int test(lua_State *L);
static int test(lua_State *L) {
    std::cout << "Testing." << std::endl;
    return 0;
}

extern "C" {
    __declspec(dllexport) int luaopen_test(lua_State *L) {
        luaL_Reg lib[] = {
            {"test", test},
            {NULL, NULL}
        };

        luaL_newlib(L, lib);
        return 1;
    }
}

When I run Lua, here is the error message that I get:

C:\Users\srevrtt\lua\lua54.exe: .\scripts\main.lua:1: The specified module could not be found.

stack traceback: [C]: in function 'assert' .\scripts\main.lua:1: in main chunk [C]: in ?

As you can probably tell, I am on a 64 bit Windows machine. Here is my Makefile:

CC= g++
ARGS= -std=c++17 -g -Wall -O3
LIBS= -lmingw32 -llua54

build:
    ${CC} -c ./src/*.cpp ${ARGS}
    ${CC} -shared *.o -o bar/test.dll


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source