lua-users home
lua-l archive

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


aircooledspeed wrote:
> 
> If I create a variable using (for example):
> 
> lua_pushstring(L, "Hello world");
> lua_setglobal(L, "MyHelloString");
> 
> Is there any way to make that variable read only (or 'constant') in
> the script, ie any attempt to change their value results in an error?

You can make the value a userdata, and use the setglobal tag method to
protect it.  But this only works for globals.  It won't work on local
variables.

#include "lua.h"

static int const_tag;

static int my_const (lua_State *L) {
  lua_settop(L,1);
  lua_pushusertag(L, (void*)lua_ref(L,1), const_tag );
  return 1;
}

static int get_const (lua_State *L) {
  lua_getref(L, (int)lua_touserdata(L,2) );
  return 1;
}

static int set_const (lua_State *L) {
  lua_settop(L,1);
  lua_pushstring(L, " is a constant so I'm not going to let you change
it" );
  lua_concat(L,2);
  lua_error(L, lua_tostring(L,-1) );
  return 0;
}

void lua_const_open (lua_State *L) {
  const_tag = lua_newtag(L);
  lua_register(L, "const", my_const );
  lua_pushcfunction(L, get_const );
  lua_settagmethod(L, const_tag, "getglobal");
  lua_pushcfunction(L, set_const );
  lua_settagmethod(L, const_tag, "setglobal");
}

Here is an example:

$ ./lua
Lua 4.0  Copyright (C) 1994-2000 TeCGraf, PUC-Rio
> x = const(44)
> print(x)
44
> y = const"this is a test"
> print(y)
this is a test
> y=55
error: y is a constant so I'm not going to let you change it
stack traceback:
   1:  `setglobal' tag method [C]
   2:  main of string "y=55" at line 1
> x = 2
error: x is a constant so I'm not going to let you change it
stack traceback:
   1:  `setglobal' tag method [C]
   2:  main of string "x = 2" at line 1
> 

Cheers,

- Peter