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

Add 'getmetatable' and 'setmetatable' to sandbox #121 #122

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 25 additions & 0 deletions Scripts/Tests/metatable.lua
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
-- Should succeed
-- User created tables can have their metatables changed
setmetatable({},{})

-- Should fail
protectedTables = {
string,
math,
string,
table,
math,
coroutine,
os,
}

function modifyProtectedTable(t)
setmetatable(t, {})
end

for _, t in ipairs(protectedTables) do
local code, msg = pcall(modifyProtectedTable, t)
if(code ~= false or msg:match("cannot change a protected metatable$") == nil) then
print("ERROR: Protected table was modified!")
end
end
20 changes: 20 additions & 0 deletions Scripts/sandbox.lua
Original file line number Diff line number Diff line change
Expand Up @@ -256,7 +256,27 @@ function sandbox.createNew(aiID, scriptName)
end

sb.require = sb.dofile

sb.setmetatable = setmetatable
sb.getmetatable = getmetatable

protectMetatables(sb)

return sb
end

function protectMetatables(t)
if type(t) ~= "table" then
return
end

local metatable = getmetatable(t) or {}
metatable.__metatable=false -- Protect metatable, cannot be modified anymore
setmetatable(t, metatable)

for _, v in pairs(t) do
protectMetatables(v)
end
end

return sandbox