Search code examples
lualua-tablemetatablenlua

What exactly is setmetatable, and how do I avoid it for security reasons?


Generally sandboxes block setmetatable like shown here:

local function memoize(f)

  local mt = {}
  local t = setmetatable({}, mt)

  function mt:__index(k)
    local v = f(k)
    t[k] = v
    return v
  end

  return t
end

The question is, I want to not use setmetatable. What is it exactly and how would I get around it? Is it simply a global variable that is a copied 'mt' variable in the above case? Is there something specific I should be doing?

Thanks.


Solution

  • Sandboxes written by competent developers don't block the regular setmetatable function. For example, Wikipedia uses the Scribunto extension, which allows anyone to write and run Lua on the site, and it allows unrestricted use of setmetatable. (It does, however, block debug.setmetatable, along with most of the rest of debug.) In general, when a sandbox does block setmetatable, it's because its developers either don't understand how userdata works, don't understand that debug.setmetatable and setmetatable are different, and/or don't understand what __metatable does. There's no need for you to restrict it.