Rapptz / sol

A C++11 Lua wrapper
MIT License
209 stars 32 forks source link

Sandbox #29

Closed DominikMS closed 10 years ago

DominikMS commented 10 years ago

Sandboxing is very usefull while you want to load more than one file (ex. for handlers, callbacks). This code is not working under 5.2, function lua_setfenv is missing.

        lua_State* l = L.get();
        if(luaL_loadfile(state, filename.c_str())) {
            lua_error(state);
            return;
        }

    // create env table
    lua_newtable( state );
    int envTable = lua_gettop( state );
    lua_newtable( state );

    // set the env
    lua_setfenv( state, -2 );

    // copy _G
    lua_newtable( state );
    int __index = lua_gettop( state );
    lua_pushstring( state, "__index" );
    lua_getfield( state, LUA_GLOBALSINDEX, "_G" );
    lua_settable( state, __index );

    // set the metatable for the env table
    lua_setmetatable( state, envTable );

    // set the env
    lua_pushvalue(state, -1);
    lua_setfield(state, LUA_GLOBALSINDEX, name.c_str());

    lua_setfenv( state, -2 );

    lua_pcall(state, 0, -1, 0);
ThePhD commented 10 years ago

I can't help you here. I don't even know what Sandboxing means in terms of Lua. I'm not even sure this is related to sol: we don't provide debugging and helpdesking for general Lua issues. If you're trying to make a feature-request to support "Sandboxing", whatever that is supposed to be in this situation, please be more clear about that. If this is just a general Lua question, I can't help you.

Rapptz commented 10 years ago

Lua 5.2 removed that method of sandboxing. I don't plan on supporting the other much more verbose way of sandboxing any time soon and I never plan on supporting Lua 5.1.

You can do it yourself. See here for more details: http://stackoverflow.com/a/6982080/1381108 sol::state has a member function to return the managed state, lua_state. So you can do what you want manually on the Lua side if you feel something is missing. The only gotcha is that you can't delete it because it's managed internally by sol::state.

DominikMS commented 10 years ago

I have do it in lua, now is easy to add this to c++. Thread can be closed.

g_test = setmetatable({}, { __index = _G })
loadfile("script2.lua", "g_test", g_test)()