I'm learning to use Lua to embed in my C programs. I was wondering what they best way make sure that my C program can find the Lua files after it's built. I'm trying to make sure this works with an out of source CMake build.
Here is what I have so far.
In my c file, I have...
int runLuaHelloWorld() {
lua_State *L = luaL_newstate();
luaL_openlibs(L);
luaL_dofile(L, "helloWorld.lua");
lua_close(L);
return 0;
}
In my CMakeLists.txt I have.
set(EMBEDDED_LUA_SRC embeddedLua.c embeddedLua.h)
add_library(embeddedLua ${EMBEDDED_LUA_SRC})
if(LUA_FOUND)
target_include_directories(embeddedLua PRIVATE ${LUA_INCLUDE_DIR})
target_link_libraries(embeddedLua ${LUA_LIBRARIES})
add_custom_command(TARGET embeddedLua POST_BUILD COMMAND ${CMAKE_COMMAND} -E copy $<TARGET_FILE:embeddedLua> helloWorld.lua)
endif()
This successfully copies it to my build directory. But it seems to load my lua script file relative to my current working directory. In other words, I can only get the script to run if I'm running it from my build folder.
What's the best practice for including and running external lua files post build?
Perhaps I'm going about this completely the wrong way. Maybe this isn't a build issue at all. The lua script needs to run relative to the executable (or better yet, relative to a library) rather than to my working directory.
Any idea?
In our software we define a path to a directory where we store extensions written in Lua. Then we use the opendir(), readir() etc. to find files in that directory, and when they end in '.lua' we load and execute them. So use just need to copy their scripts to that location.
In some applications we even store the Lua scripts in a text column of a (PostgreSQL) database table.