简体   繁体   中英

Lua functions — a simple misunderstanding

I'm trying to develop a function which performs math on two values which have the same key:

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)

The problem is that the function is attempting math on literally "operator.has.x" instead of "operator.has.a".

I'm able to call a function (x) return x.something end, but if I try function (x) something.xi get an error. I need to improve my understanding of functions in Lua, but I can't find this in the manuals.

I'm not exactly sure what you're trying to do, but here is some working code that is based on your code:

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'))

Prints '0.9'

This is a common gotcha for newcomers to the language. Buried in the Lua manual somewhere :

To represent records, Lua uses the field name as an index. The language supports this representation by providing a.name as syntactic sugar for a["name"].

This explains why your function Result(x) is failing. If you translate the syntactic sugar, your function becomes:

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

Geary already offered a solution to this so I won't reiterate it here.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM