lua-users home
lua-l archive

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


"Peter LaDow" <pladow@gmail.com> writes:

> I'm not sure if the subject aptly describes my question.  But it'll have to do.
> 
> I've spent the last day doing google searches and perusing the mailing
> list archives.  Seems what I am looking for may be common, but I can't
> find exactly what I'm looking for.
> 
> What I'd like to do is have a Lua script expose a list of functions
> that are callable from C/C++.  But I do not want to "execute" the Lua
> script.  For example, assume I have the following script (call it
> foo.lua):
> 
> function foo()
>   print "foo"
> end
> 
> function bar()
>   print "bar"
> end
> 
> And in my C/C++, I do the following:
> 
> luaL_loadfile(L, "foo.lua");
> 
> But immediately following this with something like:
> 
> lua_getglobal(L, "foo");
> 
> Returns nil, since the script has not been run yet (i.e. with a call
> to lua_call/lua_pcall).  Since I am not the owner of such Lua scripts,
> I only want to call specific functions, not to have the script run any
> arbitrary code.  For example, if the user did something like:
> 
> function foo()
>   print "foo"
> end
> 
> print "I want to do whatever I want!  Who cares about the side effects!"
> 
> Now loading and running such as script has a side effect.
> 
> How can I load a Lua script and call a function without any other side
> effects (such as executed code)?  Perhaps more like a compile and
> load, without the execution?

Block chunk or functions, whatever name you use, they are more or less the
same. What you probably want to do is:

- luaL_loadfile()
- lua_setfenv() on the resulting chunk, with an empty environment table.
- lua_pcall() on the chunk. It won't be able to have side effects because
if you put nothing into the environment table, then the assumed-unsecure
script that you loaded cannot do anyting to the host. Besides that, it will
be allowed to run forever in an infinite loop, which is a thing that you can
prevent with debug hooks.

- lua_getgloal() to get one of the functions that the loaded script had to
create, and then call them.

Unless you want those functions to only take parameters and then return a
value (processing-only functions), you may want to issue a lua_setfenv() on
each of them to provide them a set of allowed functions.

Those functions could be the harmless "print", or you could proxy some
potentially dangereous functions to add proper checks.

-- 
folays