Created
April 11, 2016 22:17
-
-
Save Qix-/c455a86b054181b1b4d79efab19aef8f to your computer and use it in GitHub Desktop.
Lua sandboxing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
this quick and dirty example shows how a program can | |
mount a new table as the global table, run some code, | |
restore the original global table and then refer to the | |
'child' global table as a regular ol' table in the parent | |
global's scope. | |
expected output: | |
global | |
type id 0 | |
is nil 1 | |
inner global: inner global | |
outer global: global | |
inner global: inner global | |
*/ | |
#include <iostream> | |
#include "lua.hpp" | |
using namespace std; | |
int main() { | |
lua_State *L = luaL_newstate(); | |
lua_pushstring(L, "global"); | |
lua_setglobal(L, "globalstring"); | |
lua_getglobal(L, "globalstring"); | |
cout << lua_tostring(L, -1) << endl; | |
lua_pop(L, 1); | |
lua_pushglobaltable(L); | |
lua_newtable(L); | |
lua_rawseti(L, LUA_REGISTRYINDEX, LUA_RIDX_GLOBALS); | |
lua_getglobal(L, "globalstring"); | |
if (lua_isstring(L, -1)) { | |
cout << "string " << lua_tostring(L, -1) << endl; | |
} else { | |
cout << "type id " << lua_type(L, -1) << endl; | |
cout << "is nil " << (lua_type(L, -1) == LUA_TNIL) << endl; | |
} | |
lua_pop(L, 1); | |
lua_pushstring(L, "inner global"); | |
lua_setglobal(L, "globalstring"); | |
lua_getglobal(L, "globalstring"); | |
cout << "inner global: " << lua_tostring(L, -1) << endl; | |
lua_pop(L, 1); | |
lua_pushglobaltable(L); | |
lua_pushvalue(L, -2); | |
lua_remove(L, -3); | |
lua_rawseti(L, LUA_REGISTRYINDEX, LUA_RIDX_GLOBALS); | |
lua_getglobal(L, "globalstring"); | |
cout << "outer global: " << lua_tostring(L, -1) << endl; | |
lua_pop(L, 1); | |
lua_getfield(L, -1, "globalstring"); | |
cout << "inner global: " << lua_tostring(L, -1) << endl; | |
lua_pop(L, 2); | |
lua_close(L); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment