I'm trying to use a custom DLL from within Lua. I have a simple DLL, for example, like
extern "C"
{
static int function_1(lua_State* L)
{
std::cout << "[DLL]this is a custom function" << std::endl;
lua_pushnumber(L, 10);
return 1;
}
__declspec(dllexport) int __cdecl luaopen_myDLL(lua_State* L)
{
L = luaL_newstate();
luaL_openlibs(L);
std::cout << "[DLL] being initialized!" << std::endl;
lua_register(L, "fun1", function_1);
luaL_dofile(L, "./run.lua");
return 1;
}
}
written in VS and built as dll.
After running within Lua
package.loadlib("./myDLL.dll", "luaopen_myDLL")()
or
require("myDLL")
the DLL is loaded and runs like expected and also runs the specified run.lua that execute function_1 just fine.
The run.lua has nothing special in it, just something like
f = function_1()
print("[Lua] Function_1 says", f, "\n");
My current issues now are:
I cannot run function_1() from the initial Lua script calling the DLL. Trying to do that I get
attempt to call global 'function_1' (a nil value)
i must use
L = luaL_newstate();
inside my C code. For some reason, it doesn't work with the passed lua_State*, which I think is the reason why I cannot call the registered functions from the LUA script loading my DLL. Before running luaL_newstate() my lua_State has a valid address which doesn't change after the newstate.
I could theoretically run any Lua script from within my C library executing the registered functions, but this seems more like a dirty workaround to me.
My question now is if I'm missing something essential?
p.s.: I'm using Lua 5.1
fun1
instead offunction_1
. – Egor Skriptunofflua_State*
instead of creating new one withluaL_newstate
. What error are you getting when using passed Lua state? – Egor Skriptunoff