0

我将 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
4

1 回答 1

1

我建议使用 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 -- when using only numeric indices
    If elem.value == "ON" then
      DoSomethingWith(elem.value, N)
    end
end
于 2019-08-25T23:28:14.527 回答