| Message |
If you set your mind to it, you can make constants by putting them in a table, and with metatables make it so you can't change it.
This example demonstrates that:
function protect_table (tbl)
return setmetatable ({},
{
__index = tbl, -- read access gets original table item
__newindex = function (t, n, v)
error ("attempting to change constant " ..
tostring (n) .. " to " .. tostring (v), 2)
end -- __newindex
})
end -- function protect_table
-------------------------- test -----------------
my_constants =
{
WIDTH = 22,
HEIGHT = 44,
FOO = "bar",
}
-- protect my table now
my_constants = protect_table (my_constants)
-- test it
print ("WIDTH", my_constants.WIDTH) --> WIDTH 22
print ("HEIGHT", my_constants.HEIGHT) --> HEIGHT 44
my_constants.WIDTH = 44 --> Error: attempting to change constant WIDTH to 44
The function 'protect_table' makes a copy of the original table, and returns an empty one, with a metatable attached to it. The metatable allows read access (via __index) but stops write access (via __newindex). |
- Nick Gammon
www.gammon.com.au, www.mushclient.com | top |
|