1

I am new to embedding Lua to C++ and currently trying to learn and hone my skills before embedding lua into a bigger project.

Here is my C++ code:

int main()
{

    int result=0;

    lua_State *L = luaL_newstate();

    static const luaL_Reg lualibs[] =
    {
        { "base", luaopen_base },
        {"math",luaopen_math},
        {"table", luaopen_table},
        {"io",luaopen_io},
        { NULL, NULL}
    };

    const luaL_Reg *lib = lualibs;
    for(; lib->func != NULL; lib++)
    {
        lib->func(L);
        lua_settop(L, 0);
    }

int status=luaL_dofile(L,"example.lua");
if(status == LUA_OK)
   {
       result = lua_pcall(L, 0, LUA_MULTRET, 0);
   }
   else
   {
       std::cout << " Could not load the script." << std::endl;
   }
printf("\nDone!\n");
lua_close(L);

return 0;

}

example.lua:

print("Hello from Lua")
print(3+5)
x=math.cos(3.1415)
print(x)

The output is:

Hello from Lua
8
Could not load the script.

Done!

Although I am loading the math library (or I think I am loading) with luaopen_math, it seems that math.cos function is not working.

What might be going on? And can you please explain if there is a simpler way of loading all of the Lua libraries to be able to run a complex Lua script.

macroland
  • 973
  • 9
  • 27
  • 1
    Why not simply call `luaL_openlibs` ? – Egor Skriptunoff Feb 08 '14 at 07:56
  • Thanks a lot! It worked very well.
    What is the difference (performance, size ...) between individually loading libraries and loading with luaL_openlibs.
    – macroland Feb 08 '14 at 09:08
  • [luaL_openlibs](http://www.lua.org/source/5.2/linit.c.html#luaL_openlibs) does more than you do. In particular, it sets globals via `luaL_requiref`. – lhf Feb 08 '14 at 14:10
  • You can (and are encouraged to) customize the libraries you need by including a modified copy of `linit.c` in your project. – lhf Feb 08 '14 at 14:11
  • In 5.2, the `luaopen*` functions have been replaced with `luaL_openlibs`. – Joel Cornett Sep 26 '15 at 11:13

0 Answers0