Lua functions - a simple misunderstanding

I am trying to develop a function that does math with two values ​​that 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 mathematically tries literally "operator.has.x" instead of "operator.has.a".

I can call the function (x) return x.something end, but if I try the function (x) something.x, I get an error. I need to improve my understanding of functions in Lua, but I cannot find it in the manuals.

+4
source share
2 answers

I'm not quite sure what you are trying to do, but here is some kind of working code 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'

+6
source

This is common news for beginners in this language. Buried in the Lua manual somewhere :

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

This explains why your function Result(x) not working. If you translate syntactic sugar, your function will look like this:

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

Geary has already proposed a solution, so I will not repeat it here.

+2
source

Source: https://habr.com/ru/post/1481453/


All Articles