lua-users home
lua-l archive

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


Am 04.05.2015 um 04:16 schröbte Ignacio Burgueño:
Hi.

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.

I usually use something like

    local s = [[
    local logger, RLC = ...
    return function (cpu)
      -- some code
    end
    ]]

    local f = assert(load(s, s, "t", {}))(logger, RLC)

for this.


Regards,
Ignacio


Philipp