虽然我了解基本的difference between .
and :
,但我还没有完全弄清楚Lua何时允许使用冒号语法。例如,类似的方法确实可以工作:
s = "test"
-- type(s) is string.
-- so I can write a colon function for that type
function string:myFunc()
return #self
end
-- and colon function calls are possible
s:myFunc()
但是,相同的模式似乎不适用于其他类型。例如,当我有一个
table
而不是string
时:t = {}
-- type(t) is table.
-- so I can write a colon function for that type
function table:myFunc()
return #self
end
-- Surprisingly, a colon function call is not not possible!
t:myFunc() -- error: attempt to call method 'myFunc' (a nil value)
-- But the verbose dot call works
table.myFunc(t)
转到另一种类型:
x = 1
-- type(x) is number.
-- So I was expecting that I can write a colon function
-- for that type as well. However, in this case even this
-- fails:
function number:myFunc()
return self
end
-- error: attempt to index global 'number' (a nil value)
我目前正试图弄清这一点。结论是否正确?
某些类型,例如
string
允许同时进行结肠功能定义和结肠功能调用。其他类型,例如
table
仅允许使用冒号功能定义,而不允许使用冒号功能调用。其他类型,例如
number
都不允许。这些差异的确切原因是什么?是否有所有类型的列表,显示它们支持的冒号语法类型?
number
情况是否有解决方法,允许编写例如x:abs()
?
最佳答案
string
上的第一个示例之所以有效,是因为所有字符串共享相同的元表,并将其存储在名为string
的表中。
从string
:
字符串库在表string
中提供了其所有功能。它还为__index
字段指向string
表的字符串设置一个元表。因此,您可以使用面向对象样式的字符串函数。例如,string.byte(s,i)
可以写为s:byte(i)
。table
上的第二个示例不起作用,因为每个表都有自己的元表,名为table
的表只是表库所有功能的集合。
像数字这样的类型默认情况下不支持metatable。
关于lua - Lua:什么时候可以使用冒号语法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33052241/