Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Lua, can I disable parts of the language from C++?

Tags:

c++

lua

Lets say I have Lua embedded in C++ app. The question may sound strange but I am interested, is there a standard way to disable Lua features from C++ side?

For example I would like to disable new variable creation except for a few defined, like this:

local time = 10
local size = 20
function test()
  return time * size
end

I would like to make Lua VM fail if I define anything else than time, size and test function. Is this possible not hacking the VM itself?

Or for example I would like to disable loops(both for and while statements).

like image 368
lukas.pukenis Avatar asked Dec 14 '22 16:12

lukas.pukenis


2 Answers

Restricting the names of global variables that can be created or accessed is easy: just load your script with an environment that has appropriate metamethods for __index and __newindex.

Restricting the names of local variables requires some deep hacking and is probably not worth it, since they cannot affect the host program.

Restricting keywords can't be done out of the box but can be done with some a simple hack:

To remove some keywords, simply add a space to the relevant strings in luaX_tokens in llex.c. These keywords will be available for variable names and the corresponding syntactical construct will not be accessible and will raise an error. For example, to remove loops, disable for, while, and repeat. You may leave in and until, but they won't do anything. If you want to do this dynamically, see this lua-l message.

like image 150
lhf Avatar answered Dec 29 '22 01:12

lhf


No, there aren't any flags for disabling core features of the language. And there couldn't possible be anything like a compile-time flag for "only allow X variables" in any reasonable way.

Modifying lua to remove for and while might be fairly straightforward but modifying it to not allow creation of variables may not (and I think probably won't) be very easy.

Something like metalua would actually make that sort of thing easier I think.

like image 38
Etan Reisner Avatar answered Dec 29 '22 01:12

Etan Reisner