Function Lua-函数声明中的变化

Function Lua-函数声明中的变化,function,lua,Function,Lua,我对Lua很陌生,对函数是如何声明的有点困惑 这两种变化似乎有效:- 第一个变体 test = {calc = function (x,y) z = x + y return z end } result = test.calc (1,2) print (result) test = {} function test.calc(x,y) z = x + y return z end result = test.calc (1,2) print (result)

我对Lua很陌生,对函数是如何声明的有点困惑

这两种变化似乎有效:-

第一个变体

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

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

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

result = test.calc (1,2)
print (result)
第二个变体

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

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

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

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

选择一个特定的变异有什么意义吗?

它们有完全相同的效果。根据可读性选择一个或另一个。(我更喜欢第二个。)

Lua没有函数声明。它具有函数定义,这些定义是在运行时计算时生成函数值的表达式(第一个变量)。其他语法形式实际上是函数定义表达式和赋值的组合

在第三个变量中,它加上一个隐式的第一个参数
self
。它用于字段的“方法调用”。方法调用只是函数调用的另一种形式,它将保存字段(函数值)的表值作为隐式第一个参数传递,以便函数可以引用它,尤其是访问它的其他字段

第三种变化:方法

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)

没有区别,更正第一个变量:
test={calc=function(x,y)z=x+y return z end}
另外,使用
local z=…
。好的,谢谢..这就解开了谜团!要学的东西太多了!与
localtest={}
存在一些差异。在这种情况下,funciton无法访问表本身。但是可以通过
localtesttest={}