从C ++调用Lua 5.2的简单查询

我刚开始学习将 Lua 嵌入到 C++ 中,目前正在尝试在嵌入到更大的项目之前学习和磨练我的技能。

这是我的 C++ 代码:

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)

输出是:

Hello from Lua
8
Could not load the script.

Done!

虽然我使用了 luaopen_math 加载了 math 库(或者我认为我是在加载),但是似乎 math.cos 函数无法工作。

可能出了什么问题?请问是否有更简单的方法来加载所有 Lua 库以便运行复杂的 Lua 脚本。

点赞