lua 和方法,混乱

lua and methods, confusion

我正在尝试找出如何在我的代码中使用方法,这让我很困惑

我尝试使用此代码:

string.testfunc = function(s) print(s) end
a="foo"
a:testfunc() --inputting a non-string value into the function gives an error

>foo

然后我尝试了这段代码

table.testfunc = function(s) print(s[1]) end
a={1,2}
table.testfunc(a)

>1

a:testfunc() --this will always error, no matter the type of the varible

>method 'testfunc' is not callable (a nil value)

我怎么可以在字符串 table 中创建一个方法,并且它可以很好地处理字符串而不是 tables?为什么用 tables 制作一个不起作用?

Lua 中的字符串库为所有字符串设置了一个索引元方法。

Lua中的table库没有为所有table设置索引元方法,因为table是用来表示对象的。通常相同 class 的对象共享相同的元 table.