Lua 中的一组链接 IUP 句柄的泛化

我正在使用 Lua 和 IUP,有一些 IUP 句柄对,如下所示:

UseField1 = iup.toggle {blah blah blah}
Field1Label = iup.text {blah blah blah}

字段对的数量(maxFields)目前为5,但可能会变化。

在我的 Lua 程序的各个地方,我需要执行以下类似操作:

for N in 1,maxFields do
    If UseFieldN.value =="ON" then
      DoSomethingWith(FieldNLabel.value, N)
    end
end

我知道我不能构造动态变量名,但是是否有一种简洁的循环方式来编写这个循环,而不是:

If UseField1 =="ON" then DoSomethingWith(Field1Label.value, 1) end
If UseField2 =="ON" then DoSomethingWith(Field2Label.value, 2) end
etc
点赞
用户1898478
用户1898478

我建议使用 Lua 表格。

t = {}
t.UseField1 = iup.toggle {blah blah blah}
t.Field1Label = iup.text {blah blah blah}
...

或者

t[1] = iup.toggle {blah blah blah}
t[2] = iup.text {blah blah blah}
...

然后循环遍历表格中的元素:

for index,elem in pairs(t) do
    If elem.value == "ON" then
      DoSomethingWith(elem.value, N)
    end
end

或者

for index,elem in ipairs(t) do -- 使用仅包含数字索引时
    If elem.value == "ON" then
      DoSomethingWith(elem.value, N)
    end
end
2019-08-25 23:28:14