Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/lua/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Methods lua表中的方法看起来像什么_Methods_Lua - Fatal编程技术网

Methods lua表中的方法看起来像什么

Methods lua表中的方法看起来像什么,methods,lua,Methods,Lua,标题说明了其中的大部分内容,但如果不完全理解,我的意思是表中的一段数据如下所示: local myTable = {"banana","apple"} -- or local myTable = {["banana"] = 1,["apple"]=2,} -- functions look like this: local myTable = { function banana(args) print(args)

标题说明了其中的大部分内容,但如果不完全理解,我的意思是表中的一段数据如下所示:

local myTable = {"banana","apple"}
-- or
local myTable = {["banana"] = 1,["apple"]=2,}
-- functions look like this:
local myTable = {
  function banana(args) print(args) end,
  -- or
  apple = function(args) print(args) end
}
t.method(2)--returns 2
t.method(t)--returns t

但是我不确定一个方法是什么样的。。。当然,我可以把它们放在桌子外面,但我更喜欢放在桌子里。。。然而,当我查看正常的“字典/库”时,我并没有真正看到任何看起来像我需要的东西

您在lua中所指的方法可能是表中的函数

t={method=function(a) return a end}
您可以这样调用此函数:

local myTable = {"banana","apple"}
-- or
local myTable = {["banana"] = 1,["apple"]=2,}
-- functions look like this:
local myTable = {
  function banana(args) print(args) end,
  -- or
  apple = function(args) print(args) end
}
t.method(2)--returns 2
t.method(t)--returns t
但是,如果使用冒号调用此函数,则它会将table
t
作为第一个参数传递:

t:method()--returns 't'
t:method(2)--still returns 't'
事实上,这相当于这样称呼它:

local myTable = {"banana","apple"}
-- or
local myTable = {["banana"] = 1,["apple"]=2,}
-- functions look like this:
local myTable = {
  function banana(args) print(args) end,
  -- or
  apple = function(args) print(args) end
}
t.method(2)--returns 2
t.method(t)--returns t
此外,如果第一个参数打算用作“方法”,那么命名它是很有必要的。因此:

t={method=function(self, a) return a end}
t.method()--returns nil
t.method(1)--returns nil
t.method(1, 2)--returns 2
t:method()--returns nil
t:method(1)--returns 1
t:method(1, 2)--returns 1

Lua中没有方法,只有
语法。你读过吗?有一个例子看起来很像您要找的。@AKX好的,那么语法sugar的意思是它与表中的普通函数相同,但执行时略有不同?(就像我表格中函数a和函数b之间的区别)你的香蕉和苹果使用了另一种形式的语法sugar,即
a=function()end
function a()end
是等效的。好吧,我再次阅读了文档,我现在明白了这是如何工作的了。。。很抱歉打扰你