【问题标题】:Why the interpreter complains that library named "math" does not exist?为什么解释器抱怨名为“math”的库不存在?
【发布时间】:2021-04-14 00:14:48
【问题描述】:

为什么解释器会抱怨名为“math”的库不存在?

据我所知,这个库是在 Lua-5.3.5 上调用 luaL_newstate 时加载的。

#include "lua.hpp"
#include <iostream>
#include <assert.h>
#include <fstream>

int main()
{
    struct lua_State *L = luaL_newstate();

    int ret;

    std::string fileName("co.lua");
    if(fileName.empty())
    {
        std::cout << "the filename is empty" << std::endl;
        return -1;
    }

    std::ifstream fileScript(fileName, fileScript.in|std::ios::ate);

    if(!fileScript.is_open())
    {
        std::cout << "open file failed" << std::endl;
        return -2;
    }

    size_t size = fileScript.tellg();

    if(size <= 0)
    {
        std::cout << "file has no valid content" << std::endl;
        return -3;
    }

    std::string textCont(size, '\0');

    fileScript.seekg(0);
    fileScript.read(&textCont[0], size);

    if((ret=luaL_loadbuffer(L, textCont.data(), textCont.length(), "co.lua")) == LUA_OK)
    {
        if((ret=lua_pcall(L, 0, LUA_MULTRET, 0)) != LUA_OK)   
        {
            std::cout << "error in invoking lua_pcall():" << ret << std::endl;
            if(lua_isstring(L, -1))
            {
                const char *errMsg = lua_tostring(L, -1);
                lua_pop(L, 1);
                std::cout << "script run encounter err:" << errMsg << std::endl;
            }
        }
    }
}

这是名为“co.lua”的文件的代码sn-p(非常简单):

  a = 1;
  b=2;

  a=a+1;
  math.sin(a)

这是控制台中的错误消息:

error in invoking lua_pcall():2
script run encounter err:[string "co.lua"]:29: attempt to index a nil value (global 'math')

【问题讨论】:

    标签: lua


    【解决方案1】:

    The documentation states,您需要致电 luaL_openlibsluaL_requiref,但您发布的程序似乎并非如此。

    要访问这些库,C 宿主程序应调用luaL_openlibs 函数,该函数会打开所有标准库。

    或者(强调我的):

    或者,宿主程序可以单独打开它们,使用luaL_requiref调用:

    • luaopen_base(用于基础库)
    • luaopen_package(用于包库)
    • luaopen_coroutine(协程库)
    • luaopen_string(用于字符串库)
    • luaopen_utf8(用于 UTF8 库)
    • luaopen_table(表库用)
    • luaopen_math(用于数学库)
    • luaopen_io(用于 I/O 库)
    • luaopen_os(用于操作系统库)
    • luaopen_debug(用于调试库)。 这些函数在lualib.h 中声明。

    因此,将程序的前几行更改为如下所示。

    You also need to compare the return value 来自 luaL_newstateNULL 并处理该错误情况。

    int main()
    {
        struct lua_State *L = luaL_newstate();
        if( L == NULL ) {
            puts( "Lua failed to initialize." );
            exit(1);
        }
    
        luaL_openlibs( L );
    
        // etc
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-05-13
      • 2012-12-05
      • 2015-06-09
      • 2020-08-12
      • 2016-02-27
      • 1970-01-01
      • 2012-03-28
      • 2016-11-01
      相关资源
      最近更新 更多