lua-users home
lua-l archive

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


在 2015/5/4 10:16, Ignacio Burgueño 写道:
Hi.

I'm writing some code where I need to generate functions based on a string template.

For instance, in the following template:
[[
function (cpu)
  logger.debug("RLC %s")
  cpu.%s = RLC(cpu, cpu.%s)
  cpu.PC = (cpu.PC + 2) & 0xffff
end
]]

"logger" and "RLC" are locals. I'm loading that template with load and when running the resulting function, it complains about "logger" being nil.

I could provide a table with those variables, but I have many besides those three, and they depend on the given template. Also, I'd like to avoid those variables being resolved as globals.

Is there any way I could "inject" locals into the function?

I thought about changing the template to:
[[
local logger, RLC
function (cpu)
  logger.debug("RLC %s")
  cpu.%s = RLC(cpu, cpu.%s)
  cpu.PC = (cpu.PC + 2) & 0xffff
end
]]
and then using debug.getupvalue / setupvalue to bind those locals. This seems to be feasible, but I'd like to know if there is an easier way.


if you do not want to use the debug library, the two ways I know to talk to a chunk are:
 1) globals/`_ENV` (via the `load` function or `setfenv` for Lua 5.1);
 2) chunk arguments (a chunk is essencially a vararg function)

otherwise, the debug library is your only choice. you must first declare locals in the chunk
to allocate slots for them, then use `debug.setlocal` or `debug.setupvalue` or `debug.upvaluejoin`
to modify them.

Regards,
Ignacio


--
the nerdy Peng / 书呆彭 / Sent from Thunderbird