When trying to require a shared library (.dll) in Lua, I get the error "attempt to call global 'require'"

Viewed 55

I'm currently working with a system that uses Lua for scripting. I'd like to use C++ for some of the device peripheral logic that I have already, so I wrote a wrapper around said C++ logic so Lua could call it via a shared library. This works quite well in my own test script, which looks like the following:

myLib = require 'myLib'

myLib.callMyFunc()

However, when I try to the do the same thing in the system I'm working with, I get the following error:

attempt to call global 'require' (a nil value)

Why would this happen?

1 Answers

This question is not easy to answer because we don't see much code. It could be somewhere in the Lua code, the variable require being redefined to nil. But I don't think this is the root cause of the problem.

I believe the function luaL_newstate has been called without calling luaL_openlibs or similar functions. So, the standard library functions are not loaded in the interpreter.

I would suggest the OP to choose which standard library is necessary for his code:

basic library (§6.1);
coroutine library (§6.2);
package library (§6.3);
string manipulation (§6.4);
basic UTF-8 support (§6.5);
table manipulation (§6.6);
mathematical functions (§6.7) (sin, log, etc.);
input and output (§6.8);
operating system facilities (§6.9);
debug facilities (§6.10).

The function require belongs to the package library, so a call to luaopen_package is important:

lua_State *LuaState = luaL_newstate();

/* Open libraries */
luaopen_base(LuaState);
luaopen_package(LuaState);

For the sake of completeness, it could be interesting for future SO users to have the list of all the functions to copy/paste and adapt to their own project:

lua_State *LuaState = luaL_newstate();

/* Open libraries */
luaopen_base(LuaState);
luaopen_package(LuaState);
luaopen_coroutine(LuaState);
luaopen_string(LuaState);
luaopen_utf8(LuaState);
luaopen_table(LuaState);
luaopen_math(LuaState);
luaopen_os(LuaState);
Related