lua-users home
lua-l archive

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


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.

Regards,
Ignacio