什么时候可以使用冒号语法

什么时候可以使用冒号语法

本文介绍了Lua:什么时候可以使用冒号语法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

尽管我了解.: 之间的基本基本区别,但我还没有完全了解何时Lua允许使用冒号语法.例如,类似的方法确实可以工作:

While I understand the basic difference between . and :, I haven't fully figured out when Lua allows to use the colon syntax. For instance, something like this does work:

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时:

However the same pattern does not seem to work for other types. For instance, when I have a table instead of a 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)

我目前正试图弄清这一点.结论

I'm currently trying to make sense of this. Is it correct to conclude that

这些差异的确切原因是什么?是否有所有类型的列表,显示它们支持的冒号语法类型? number案例是否有解决方法,允许编写例如x:abs()?

What exactly is the reason for these differences? Is there a list of all types, showing which type of colon-syntax they support? Is there maybe a workaround for the number case, allowing to write e.g. x:abs()?

推荐答案

string上的第一个示例之所以有效,是因为所有字符串共享相同的元表,并将其存储在名为string的表中.

The first example on string works because, all strings share the same metatable, and it's stored in the table named string.

来自 string :


table上的第二个示例不起作用,因为每个表都有其自己的元表,名为table的表只是表库所有功能的集合.


The second example on table doesn't work because, every table has its own metatable, the table named table is just a collection of all the functions of table library.

数字之类的类型默认情况下不支持metatable.

Types like numbers don't support metatable by default.

这篇关于Lua:什么时候可以使用冒号语法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-07 03:08