Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Can't define function in lua script after calling luaL_sandbox in host #1265

Closed
Ono-Sendai opened this issue May 25, 2024 · 2 comments
Closed
Labels
bug Something isn't working

Comments

@Ono-Sendai
Copy link

After calling luaL_sandbox, which we are supposed to do apparently (according to https://github.com/luau-lang/luau?tab=readme-ov-file#building), I then execute the script with lua_pcall(state, 0, LUA_MULTRET, 0);.

In the Lua script, a new function is defined:

function f(x : number, y : number) : number
    return x + y
end

But this results in:
1: string: [string "test"]:40: attempt to modify a readonly table

So scripts can't define new functions?

Or are we supposed to execute the script first, then sandbox it? But doesn't this go against the principle of sandboxing in the first place?

@Ono-Sendai Ono-Sendai added the bug Something isn't working label May 25, 2024
@zeux
Copy link
Collaborator

zeux commented May 28, 2024

The correct procedure is that instead of running code in the (sandboxed) global state, you create new threads, sandbox them using luaL_sandboxthread and run code inside them.

So, do this once when initializing the VM:

  1. luaL_newstate
  2. luaL_openlibs plus whatever extra global setup for the shared global environment you need via luaL_register / lua_setglobal
  3. luaL_sandbox

... and then do this any time you want to start a new script:

  1. lua_newthread
  2. luaL_sandboxthread
  3. luau_load with bytecode
  4. lua_resume or lua_pcall to run it

luaL_sandboxthread will create a writeable global table for the thread that will refer to the (read-only) shared global environment for unknown keys.

@Ono-Sendai
Copy link
Author

Awesome, that seems to work so far, thank you.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug Something isn't working
Development

No branches or pull requests

2 participants