Function 表中包含参数的lua函数

Function 表中包含参数的lua函数,function,parameters,lua,Function,Parameters,Lua,我是lua的新手,希望在表中存储一个函数,参数在“存储时间”给定 尝试了这段代码,但并不是我想要的(显然) 我想将变量存储在“insert”中,因此我尝试将参数存储在表中: functable = {} function myfunc() print(functable[#functable].p1 ,functable[#functable].p2) end table.insert(functable, {func = myfunc, p1="Hello", p2="World"

我是lua的新手,希望在表中存储一个函数,参数在“存储时间”给定

尝试了这段代码,但并不是我想要的(显然)

我想将变量存储在“insert”中,因此我尝试将参数存储在表中:

functable = {}

function myfunc()
    print(functable[#functable].p1 ,functable[#functable].p2)
end

table.insert(functable, {func = myfunc, p1="Hello", p2="World"})
table.remove(functable).func()
但是这个代码不起作用


有人能给我指一下正确的方向吗?

你的代码的问题是一旦你做了
表格。删除
你的
p1
p2
就不能在
myfunc
中使用
functable[#functable]
检索。如果您输入了第二个函数,您将看到打印,但打印将与表中下一个函数的参数一起显示

table.insert(functable, {func = myfunc, p1="Goodbye", p2="World~"})
table.insert(functable, {func = myfunc, p1="Hello", p2="World!"})
table.remove(functable).func()
输出:

再见世界~


我建议的解决方案是在表中设置参数,然后在调用函数时将其应用于函数:

functable = {}

local function myfunc(x,y)
    print(x ,y)
end

table.insert(functable, {func = myfunc, params = {"Goodbye", "World~"}})
table.insert(functable, {func = myfunc, params = {"Hello", "World!"}})

local action1 = table.remove(functable)
local action2 = table.remove(functable)

action1.func(table.unpack(action1.params))
action2.func(table.unpack(action2.params))

另一种解决方案是包装函数并将参数设置为upvalues

以下是一个例子:

functable = {}

function myfunc(...)
    local params = {...}

    local function func()
        print(params[1] ,params[2])
    end

    return func
end

table.insert(functable, {func = myfunc("Goodbye", "World~")})
table.insert(functable, {func = myfunc("Hello", "World!")})

table.remove(functable).func()
table.remove(functable).func()

这是Nifim第一个变体的修改:

functable = {}

local function myfunc(x,y)
   print(x, y)
end

local F_mt = {}

function F_mt:__call()
   return self.func(table.unpack(self.params))
end

local function F(obj)
   return setmetatable(obj, F_mt)
end

table.insert(functable, F{func = myfunc, params = {"Goodbye", "World~"}})
table.insert(functable, F{func = myfunc, params = {"Hello", "World!"}})

table.remove(functable)()
table.remove(functable)()

您确实希望存储一个没有参数的类似函数,而不是存储
myfunc
。换句话说,结束:

local functable = {}

local function myfunc(x, y)
  print(x, y)
end

local function addArguments(f, ...)
  local args = {...}
  return function()
    return f(table.unpack(args))
  end
end

table.insert(functable, addArguments(myfunc, 'Hello', 'World'))
table.remove(functable)()
此解决方案与Egor的答案不同,它使用闭包而不是表来捆绑函数和参数

local functable = {}

local function myfunc(x, y)
  print(x, y)
end

local function addArguments(f, ...)
  local args = {...}
  return function()
    return f(table.unpack(args))
  end
end

table.insert(functable, addArguments(myfunc, 'Hello', 'World'))
table.remove(functable)()