Zalokin
Zalokin

Reputation: 65

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?

Upvotes: 1

Views: 128

Answers (2)

Tom Blodget
Tom Blodget

Reputation: 20812

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)

Upvotes: 0

lhf
lhf

Reputation: 72422

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

Upvotes: 1

Related Questions