lua-users home
lua-l archive

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

>From  Thu Jun 15 05:54:13 2000
>From: (Erik Hougaard)
>I would like to have a "securedostring" command... That would be a dostring
>that only would allow simple expressions and the functions defined in
>mathlib .. I would use this to allow my user to type simple expressions in
>entry fields, but I do not want my users to be able to call functions (lua
>defined) and other C functions..

If you only allow one expression at a time, then one simple solution is

 function securedostring(s)
  return dostring("return "..s)

Because of the added "return", you cannot have arbitrary Lua constructs in 's'.
But you can still have multiple expressions returned, as in
	"1+sin(x), tan(exp(random(y))"
If you don't want this, do

 function securedostring(s)
  local v=dostring("return "..s)
  return v

This still leaves the problem of 's' having calls to "unsafe" functions.
The easiest solution seems to be to evaluate this in a state that contains
noting but the "safe" functions, in your case, the ones from mathlib.
This state is easily created in Lua 4.0 with lua_newstate("builtin", 0, NULL)
and then open mathlib in this state.
The state would also contain any global variables that would be needed in
your expressions. These global variables have to set from C.

I think this is a nice example of how to use Lua as a simple expression
evaluator. I actually have begun writing a simple C library based on this
idea, to show how Lua is useful even if you don't need a full language in
your application. I might finish it now and add it to the distribution :-)
Adding an expression evaluator to C programs is a FAQ...