lua-users home
lua-l archive

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


> In 5.0, luaL_loadstring/file will compile a function of the file/string
> that you can call. (Unfortunately parameters can not be passed to it
> without kludges.)

I don't know if this classifies as a kludge -- I don't think so --
but you can just precede the function with the word "return "
(or surround a script with "return function(...) " and "end")
and then call the compiled chunk from luaL_load{string, file}
to get the callable function.

The second case lets the script access its arguments from arg.
Of course, you could put in actual parameter names if you wanted to.

For a more general solution, see LTN 11 
<http://www.lua.org/notes/ltn011.html>
which demonstrates a good mechanism for loading packages of script 
functions.
You can, as Adam suggests, let the script load its functions into globals 
--
but you better trust it not to redefine your globals. It is better, IMHO,
to put the results into a table of your choosing, for example by 
setfenv'ing
the compiled chunk before running it. Of course, if you were setfenv'ing,
you could preload the environment with whatever global variables you 
wanted
to, which would in effect be parameters of a sort.

There is no real need to use the registry; if you are embedding Lua in
a main program, you can simply use the first few stack slots to store
whatever you like. Lua scripts cannot see these stack slots, so they
are completely safe. However, your C callbacks won't be able to see
them either, so if you are using C callbacks, you either have to use
the registry or you need to associate the script's package table
(assuming you have built one LTN-11 style) or environment table
(if you setfenv'd) with an upvalue in your C callbacks --
this is my preferred solution, and it is very little more
work than the registry solution. It works very nicely for
configuration tables, too.