Iup Lua 回调函数 -- 我做错了什么?

我正在使用 Lua 5.1 和 IUP 3.5,试图使用列表回调来根据选择的地点填充地址列表。(该列表是一个编辑框,因此我需要在适当的时候处理它,但让我们先处理基本事项)。我显然对如何做这一点有着根本性的误解。

代码如下:

function MakeAnIupBox
    --在这里添加更多的元素
    listPlace = iup.list{}
    listPlace.sort = "YES"
    listPlace.dropdown = "YES"
    --在这里填充列表
    --现在处理回调函数
    listPlace.action = function(self) PlaceAction(text, item,  state) end
end

function PlaceAction(text, item, state)
    listAddress.REMOVEITEM = "ALL"
    if state == 1 then -- 选择了地点
    --在这里编写代码来填充地址列表
    end
end

iup 文档 描述了列表的 Action 回调函数为

ih:action(text: string, item, state: number) -> (ret: number) [in Lua]

然而,当我运行这段代码时,我得到了以下结果:

  • text -- 看起来像某种元表
  • item, state -- 都是 nil

我也尝试了以下方式编写回调函数:

function MakeAnIupBox
    --在这里添加更多的元素
    listPlace = iup.list{}
    listPlace.sort = "YES"
    listPlace.dropdown = "YES"
    --在这里填充列表
end
function listPlace:action (text, item, state)
    listAddress.REMOVEITEM = "ALL"
    if state == 1 then -- 选择了地点
        --在这里编写代码来填充地址列表
    end
end

但是这段代码运行失败:错误是 attempt to index global 'listPlace' (a nil value)

我希望不要将回调函数嵌入“MakeAnIupBox”中,因为我希望将其(和其他相关的回调函数)作为可重用的组件在几个 Lua 程序中使用,这些程序都从不同的 UI 处理类似的数据集。

点赞
用户1898478
用户1898478

问题出在 Lua 的使用上。

在第一种情况下,记住这个:

function ih:action(text, item, state)

会被翻译成这个:

function action(ih, text, item, state)

所以缺少了 ih 参数。

在第二种情况下,listCase 只有在调用 MakeAnIupBox 之后才存在。你可以通过在 MakeAnIupBox 范围内声明该函数来解决这个问题。

2019-01-16 12:59:55
用户9185797
用户9185797

如果你不想将回调函数嵌入到你的函数里,你可以在函数之前定义它,之后再将它指定到你想要的位置。

function Callback(self, a, b)
   -- 做你的工作 ...
end

function CallbackUser1()
    targetTable = { }
    targetTable.entry = Callback
end

function CallbackUser2()
    otherTargetTable = { }
    otherTargetTable.entry = Callback
end

这种解决方案需要保证参数始终相同。

注意:以下所有定义是相同的

function Table:func(a, b) ... end
function Table.func(self, a, b) ... end
Table.func = function(self, a, b) ... end
2019-01-16 14:37:06
用户1943174
用户1943174

根据 Antonio Scuri 的建议(不够明确),我整理出以下代码:

function MakeAnIupBox
    --在这里添加更多元素
    listPlace = iup.list{}
    listPlace.sort = "YES"
    listPlace.dropdown = "YES"
    --在这里填充列表
    --现在处理回调
    listPlace.action = function(self, text, item, state) PlaceAction(listPlace, text, item,  state) end
end

function PlaceAction(ih, text, item, state)
    listAddress.REMOVEITEM = "ALL"
    if state == 1 then -- 选择了某个地点
    --在这里编写代码以填充地址列表
    end
end
2019-01-16 18:21:43