Re: loadstring to create a function with parameters
[
Date Prev][
Date Next][
Thread Prev][
Thread Next]
[
Date Index]
[
Thread Index]
- Subject: Re: loadstring to create a function with parameters
- From: Rici Lake <lua@...>
- Date: 2006年12月17日 11:09:04 -0500
On 17-Dec-06, at 9:10 AM, Javier Guerra wrote:
On Sunday 17 December 2006 8:18 am, Terisquas Brothers wrote:
Is there any way to convert the string funcName to a
function which accepts a single parameter?
a global function is just an anonymous function stored as a named
field in the
environment variable, usually _G
therefore:
funcXY()
is the same as:
_G["funcXY"] ()
in fact, i guess both compile to the same bytecode. (maybe using a
constant
reference for the environment, instead of _G)
_G is not magic, it's just another global. It might not even refer to
the current function environment.
In 5.1, chunks are compiled as vararg functions, not as functions of no
arguments. So a chunk can acquire its arguments easily:
-- foo.lua
local a, b, c = ...
If you want to do that with earlier versions of Lua, you can use the
"double call" mechanism:
chunk = loadstring("return function(a, b, c) " .. chunkstring .. "
end")()
Note the extra () to do the second call; you might want to replace that
with a pcall:
chunk = pcall(loadstring("return function(a, b, c) "
.. chunkstring .. " end"))