Ivan
Ivan

Reputation: 65

Lua does not load libs

I decided to add scripting with Lua. I've downloaded and compiled interpreter. It works fine, but when I want to use any functions from os.* or string.* libs, it says, that "attemt to index global 'os' (a nil value)"

Here is my code and should work, but it does not:

#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;
}

What's wrong with it?

Upvotes: 3

Views: 914

Answers (1)

lhf
lhf

Reputation: 72312

In Lua 5.2 the standard luaopen_* functions do not set the corresponding global variables.

Why not copy and adapt the code in linit.c or just call luaL_openlibs?

Otherwise, do what they do: call luaL_requiref for each luaopen_* function.

See http://www.lua.org/source/5.2/linit.c.html#luaL_openlibs.

Upvotes: 5

Related Questions