I want to let a third-party develop a Lua script that runs with my C++ application. A script may contain many individual files. To make this safe I use Luau for sandboxing. My C++ application must compile and load the third-party Luau script files as outlined in the Roblox readme. I am not able to do this with more than one file.
Let us say that script file module1.luau looks like this:
module = require("module2")
print('started module 1')
print(module.hello())
Script file module2.luau looks like this:
local M = {}
function M.hello()
return 'Hello'
end
print('started module 2')
return M
The simple C++ application (module.cpp) that loads the script files look like this:
#include <iostream>
#include <fstream>
#include <assert.h>
#include "/home/me/luau/VM/include/lua.h"
#include "/home/me/luau/VM/include/lualib.h"
#include "/home/me/luau/Compiler/include/luacode.h"
#include <gtk/gtk.h>
using namespace std;
int main()
{
lua_State* L = luaL_newstate();
luaL_openlibs(L);
string content;
ifstream ifs;
char* bytecode;
size_t bytecodeSize = 0;
ifs.open("module2.luau", ifstream::in);
content.assign( (istreambuf_iterator<char>(ifs) ),
(istreambuf_iterator<char>() ) );
bytecode = luau_compile(content.c_str(), content.length(), NULL, &bytecodeSize);
assert(luau_load(L, "foo2", bytecode, bytecodeSize, 0) == 0);
free(bytecode);
lua_pcall(L, 0, 0, 0);
ifs.open("module1.luau", ifstream::in);
content.assign( (istreambuf_iterator<char>(ifs) ),
(istreambuf_iterator<char>() ) );
bytecode = luau_compile(content.c_str(), content.length(), NULL, &bytecodeSize);
assert(luau_load(L, "foo1", bytecode, bytecodeSize, 0) == 0);
free(bytecode);
lua_pcall(L, 0, 0, 0);
lua_close(L);
return 0;
}
Running the modules by themselves gives the expected result:
$ ./luau module1.luau
started module 2
started module 1
Hello
Running module.cpp gives this:
$ g++ -Wall -o module module.cpp -L/home/me/luau/build/release -lluauvm -lluaucompiler -lluauast -lisocline -lgtk-3 -lgio-2.0 -lgobject-2.0
$ ./module
started module 2
The second compile/load does not happen. The code is obviously wrong, but how?
I presume it is possible to load individual script files so that they work together with require
in this manner. Note that there are a number of load C API functions that are available in Lua but not in Luau.