lua-users home
lua-l archive

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


=== FAQ ===

Ando Sonenblick wrote:
Gang,

Is there a way in Lua to lock a global variable after initializing it so
that trying to reassign it will fail?

We'd like to prevent inadvertent reassignment of key global variables by
some unaware scriptor...

If you want to make all globals readonly, see lua-5.0/test/readonly.lua

If you want to make only a few variables readonly, try something like this:

$ cat z.lua

local ReadOnly = {
  x = 5,
  y = 'bob',
  z = false,
}

local function check(tab, name, value)
  if ReadOnly[name] ~= nil then
    error(tostring(name) ..' is a read only variable', 2)
  end
  rawset(tab, name, value)  -- tab[name] = value
end

-- make some global variables readonly
setmetatable(_G, {__index=ReadOnly, __newindex=check})


$ lua -lz -i
>
> = x,y,z
5       bob     false
> x = 44
stdin:1: x is a read only variable
stack traceback:
        [C]: in function `error'
        z.lua:10: in function <z.lua:8>
        stdin:1: in main chunk
        [C]: ?
> z = 99
stdin:1: z is a read only variable
stack traceback:
        [C]: in function `error'
        z.lua:10: in function <z.lua:8>
        stdin:1: in main chunk
        [C]: ?
> a,b = 1,2
> = a,b
1       2
>


Here are some similar threads:
http://lua-users.org/lists/lua-l/2003-06/msg00362.html
http://lua-users.org/lists/lua-l/2003-07/msg00298.html

- Peter