lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


Dr. Markus Walther wrote:
[...]
My question therefore to the list: how would one go about replicating this in (extended?) Lua, perhaps first for tables?

My initial thoughts were to use a metatable approach with a new write-only field mt.__secure (or perhaps __protected) guarding R/W access to protected entries of main table t. mt.__secure would hold the key k to unlock t[k] (perhaps generalized to a table of such keys k_i).
A new builtin name() generates fresh keys.

Nah, you don't need any of that.

function create_secure_table()
  local data = {}
  local mt = {
    __index = function(t, k) return data[k] end,
    __newindex = function(t, k, v) data[k] = v end
  }
  local t = {
    newkey = function() return {} end
  }
  setmetatable(t, mt)
  return t
end

create_secure_table() returns the table. t:newkey() will return a new unprintable key. Accessing the table via t[k] should work normally. You can't table-walk to find existing keys because they're all safely hidden in an upvalue.

In fact, since that the overall purpose of this (if I've understood it correctly!) is to hide internal representation, none of this is necessary in Lua: hiding data in upvalues like this is far easier than fiddling about with tables, and considerably faster. In the above example, there's no way the user can get from the opaque object t to the table data that actually contains the keys (without using the debug library, but if you give that to users, you lose all pretence of security anyway).

--
David Given
dg@cowlark.com