3

I am embedding Lua in a C++ application.

I have some modules (for now, simple .lua scripts) that I want to load programmatically, as the engine is being started, so that when the engine starts, the module(s) is/are available to scripts without them having to include a require 'xxx' at the top of the script.

In order to do this, I need to be able to programmatically (i.e. C++ end), ask the engine to load the modules, as part of the initialisation (or shortly thereafter).

Anyone knows how I can do this?

2 Answers 2

5

Hmm, I just use the simple approach: My C++ code just calls Lua's require function to pre-load the Lua scripts I want preloaded!

// funky = require ("funky")
//
lua_getfield (L, LUA_GLOBALSINDEX, "require"); // function
lua_pushstring (L, "funky");     // arg 0: module name
err = lua_pcall (L, 1, 1, 0);
// store funky module table in global var
lua_setfield (L, LUA_GLOBALSINDEX, "funky");

// ... later maybe handle a non-zero value of "err"
// (I actually use a helper function instead of lua_pcall
// that throws a C++ exception in the case of an error)

If you've got multiple modules to load, of course, put it in a loop... :)

Sign up to request clarification or add additional context in comments.

Comments

4

The easiest way is to add and edit a copy of linit.c to your project.

2 Comments

Suppose my module is in /usr/local/lua/script/mymodule.lua, how would I modify linit.c to get the functionality required?. I have looked at the source code, and it seems to be for C packages not Lua scripts - am I missing something?
@skyeagle: Sorry, I assumed a C module. For a Lua module, you can set the environment variable LUA_INIT to say @loadmymodules.lua and in that load all your Lua modules with require.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.