您不能用引用函数的变量替换原生 Lua 运算符,唯一的方法是在关联数组中创建一组函数并将索引设置为对您要执行的相应操作。
查看您的列表,您有一个大于 (>) 且等于 (=)。我们为这些操作创建一个表,该表采用如下两个参数。
local operators = {
[">"] = function(x, y) return x > y end,
["="] = function(x, y) return x == y end,
-- Add more operations as required.
}
然后,您可以通过从字符串中获取操作字符以及数值本身来从 decode_prog 函数调用相应的函数 - 这是可能的,因为您可以从索引为的关联数组中获取函数我们要执行的操作的字符串。
local result = operators[op](var2, number)
这会调用operators 数组,使用op 来确定我们需要转到哪个索引以进行适当的操作,并返回值。
最终代码:
str = { '>60', '>60', '>-60', '=0' }
del = 75
local operators = {
[">"] = function(x, y) return x > y end,
["="] = function(x, y) return x == y end,
}
function decode_prog(var1, var2)
local op = string.sub(var1, 1, 1) -- Fetch the arithmetic operator we intend to use.
local number = tonumber(string.sub(var1, 2)) -- Strip the operator from the number string and convert the result to a numeric value.
local result = operators[op](var2, number) -- Invoke the respective function from the operators table based on what character we see at position one.
if result then
print("condition met")
else
print('condition not meet')
end
end
for i = 1, #str do
decode_prog(str[i], del)
end