0 Replies - 1166 Views - Last Post: 22 May 2010 - 03:12 PM

#1 athlon32  Icon User is offline

  • D.I.C Regular
  • member icon

Reputation: 117
  • View blog
  • Posts: 363
  • Joined: 20-August 08

[LUA]Make a Table Read-Only

Posted 22 May 2010 - 03:12 PM

Description: This will run perfectly (or should). However, uncommenting the bottom line will cause an error (as it should!) A function that can make any table constant and unmodifiable.
-- Lua has no constants by default. Using metatables
-- we can save the state of a table and forbid any
-- changes to it. This function does that exactly 
function makereadonly(t)
    -- the metatable
    local mt = { __index = t,
                 __newindex = function(t, k, v)
                     error("trying to modify constant field " .. tostring(k), 2)
                 end
    }
    return setmetatable({}, mt)
end


-- An example of using it
point = { x = 25, y = 35 }
point = makereadonly(point)

-- uncommenting the following line will cause an error
-- point.x = 34



Is This A Good Question/Topic? 0
  • +

Page 1 of 1