Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/lua/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Function Lua函数——一个简单的误解_Function_Lua_Lua Table - Fatal编程技术网

Function Lua函数——一个简单的误解

Function Lua函数——一个简单的误解,function,lua,lua-table,Function,Lua,Lua Table,我试图开发一个函数,对两个键相同的值执行数学运算: property = {a=120, b=50, c=85} operator = {has = {a, b}, coefficient = {a = 0.45}} function Result(x) return operator.has.x * operator.coefficient.x end print (Result(a)) error: attempt to perform arithmetic on field 'x' (a

我试图开发一个函数,对两个键相同的值执行数学运算:

property = {a=120, b=50, c=85}
operator = {has = {a, b}, coefficient = {a = 0.45}}
function Result(x) return operator.has.x * operator.coefficient.x end
print (Result(a))
error: attempt to perform arithmetic on field 'x' (a nil value)
问题是函数正在尝试对其进行数学运算 “operator.has.x”而不是“operator.has.a”


我可以调用函数(x)返回x.something end,但是如果我尝试函数(x)something.x,我会得到一个错误。我需要提高我对Lua函数的理解,但我在手册中找不到这一点。

我不太清楚您想做什么,但这里有一些基于您的代码的工作代码:

property = {a=120, b=50, c=85}
operator = {has = {a=2, b=3}, coefficient = {a = 0.45}}
function Result(x) return operator.has[x] * operator.coefficient[x] end
print (Result('a'))

打印“0.9”

这是该语言新手的常见问题。埋在Lua手册中:

为了表示记录,Lua使用字段名作为索引。这个 语言通过提供一个.name作为语法名称来支持这种表示 一个[“名字”]的糖

这解释了
函数结果(x)
失败的原因。如果您翻译语法糖,您的函数将变成:

function Result(x) 
  return operator.has['x'] * operator.coefficient['x']
end

Geary已经提供了一个解决方案,所以我在此不再重复。

这正是我想要做的!非常感谢。很酷,很高兴这很有帮助!啊,这很有道理。我可能应该避免使用任何替代符号,直到我理解了表是如何工作的。