Lua 不加载库。

我决定使用Lua添加脚本。我下载并编译了解释器。它能正常工作,但是当我想使用os。或string。库中的任何函数时,它会说“尝试索引全局变量'os'(空值)”。

这是我的代码,应该可以工作,但是并没有:

#include <iostream>
#include <Windows.h>
#include <string>

using namespace std;

extern "C" {
#include "..\liblua\lua.h"
#include "..\liblua\lualib.h"
#include "..\liblua\lauxlib.h"
}

int main(int argc, TCHAR* argv[])
{
    lua_State *LuaVM = luaL_newstate();

    lua_pushcfunction(LuaVM,luaopen_base);
    lua_call(LuaVM,0,0);
    lua_pushcfunction(LuaVM,luaopen_math);
    lua_call(LuaVM,0,0);
    lua_pushcfunction(LuaVM,luaopen_string);
    lua_call(LuaVM,0,0);
    lua_pushcfunction(LuaVM,luaopen_table);
    lua_call(LuaVM,0,0);

    int error;
    lua_pushstring(LuaVM,"Ver 0.525.5");
    lua_setglobal(LuaVM,"Version");

    while (true)
    {
        string strCode;
        getline(cin,strCode);
        error = luaL_loadbuffer(LuaVM,strCode.c_str(),strCode.length(),"") ||
            lua_pcall(LuaVM,0,0,0);
        if (error)
        {
            cout<< lua_tostring(LuaVM,-1)<<endl;
            lua_pop(LuaVM,1);
        }
    }

    lua_close(LuaVM);

    return 0;
}

它有什么问题?

点赞
用户107090
用户107090

在 Lua 5.2 中,标准的 luaopen_* 函数 不会 设置相应的全局变量。

为什么不复制并调整 linit.c 中的代码,或者直接调用 luaL_openlibs 呢?

否则,可以像它们一样:为每个 luaopen_* 函数调用 luaL_requiref

请参阅http://www.lua.org/source/5.2/linit.c.html#luaL_openlibs

2012-05-30 18:05:21