简体   繁体   中英

Lua - variations in the declaration of functions

I'm quite new to Lua and slightly confused about how functions are declared.

These 2 variations seem to work: -

1st variation

test = {calc = function (x,y)
    z = x + y
    return z
end
}

result = test.calc (1,2)
print (result)

Second variation

test = {}

function test.calc(x,y)  
  z = x + y
  return z
end

result = test.calc (1,2)
print (result)

Are there any implications of selecting a particular variation?

They have exactly the same effect. Choose one or the other based on readability. (I prefer the second one.)

Lua doesn't have function declarations. It has function definitions, which are expressions (1st variant) that produce a function value when evaluated at runtime. The other syntactical forms are effectively a combination of a function definition expression and an assignment.

In this 3rd variation, it is that plus an implicit 1st parameter self . It is intended to be used in a "method call" on a field. A method call is just an alternate form of function call that passes the table value holding the field (the function value) as an implicit 1st argument so the function can reference it, especially to access its other fields.

3rd Variation: Method

local test = { history = {} }

function test:calc(x,y)
  local z = x + y
  table.insert(self.history, { x = x, y = y })
  return z
end

print(test.calc)
local result = test:calc(1,2)
print(result)
print(test.history[1].x, test.history[1].y)

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