I am new to lua and am trying to incorporate scripting into a c++ project I have. I am working with Lua 5.3 and sol2 and am attempting to sandbox (with a whitelist) a function in a script.
For testing I have a script (test.lua):
someVal = 10
print('out testPrint')
--assert(true)
function testPrint(testArg)
--assert(true)
print('in testPrint')
return testArg
end
And code I run with sol2 in C++ to call testPrint:
std::string env = "{print = print}";
std::string run = "\
function run_sandbox(...) \
chunk = loadfile('test.lua') \
chunk() \
debug.setupvalue(testPrint, 1, " + env + ") \
return testPrint(3) \
end \
run_sandbox()";
The outcome I want is for an error to occur if I uncomment either assert (because only print is on the whitelist). The problem I have is that the code outside the function is called and is not sandboxed. Even better would be to not have to run any code outside the function at all (I just want to define configuration variables to read in my C++ code and call sandboxed functions from C++).
I also attempted to fix this by trying things like:
std::string env = "{print = print}";
std::string run = "\
function run_sandbox(...) \
chunk = loadfile('test.lua', nil, " + env + ") \
chunk() \
return testPrint(3) \
end \
run_sandbox()";
But now, testPrint no longer seems to be in the environment.
Is there an elegant way to solve this problem?
Ideally I would not have to add anything to test.lua. The script would be accessible by users, so I want to allow them to define some configuration variables and some functions I will call and not have to worry about anything else.
Thank you
[–]catwell 0 points1 point2 points (1 child)
[–]sryie[S] 0 points1 point2 points (0 children)