lua-users home
lua-l archive

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



Jean Claude Morlier wrote:
I want to export some variable (userdata, function, string,...)
from C++ to LuaState.
How can I do to set this variables ReadOnly.

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 ro.lua
-- make some global variables readonly

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

local function check(tab, name, value)
  if rawget(ReadOnly, name) then
    error(name ..' is a read only variable', 2)
  end
  rawset(tab, name, value)
end

setmetatable(_G, {__index=ReadOnly, __newindex=check})


$ lua -i ro.lua > = x 5 > = y bob > z = 'junk' > x = 4 stdin:1: x is a read only variable stack traceback: [C]: in function `error' ro.lua:11: in function <ro.lua:9> stdin:1: in main chunk [C]: ? > = x 5 > = z junk >

- Peter Shook