简体   繁体   English

如何创建自动处理表的 Lua 方法

[英]how to create Lua methods that work with tables automatically

In Lua, I see some methods such as the string and io class that allows you to call the method from the table automatically, without the need to instantiate an object for this, example: In Lua, I see some methods such as the string and io class that allows you to call the method from the table automatically, without the need to instantiate an object for this, example:

the following code:以下代码:

local tb = {"Hello", "World!"}

table.concat(tb)

can be written like this:可以这样写:

local tb = {"Hello", "World!"}

tb:concat()

I tried to create a method that could do the same thing:我试图创建一个可以做同样事情的方法:

local tst = {}

function tst:test()
     print("test")
end

but the following code does not work:但以下代码不起作用:

local tb = {"Hello", "World!"}

tb:test()

only if I inform the code that tb = tst :只有当我通知代码tb = tst时:

local tb = tst

tb:test()

my question is, there any way for me to create methods that work with a string, or a table automatically as in the second example without the need to instantiate the class?我的问题是,我有什么方法可以像第二个示例那样自动创建与字符串或表一起使用的方法,而无需实例化 class? like, calling my table as a table:MyMethod()比如,把我的表称为表:MyMethod()

I'm not sure if this answers your original question, but maybe answering your question from the comments will help explain things.我不确定这是否回答了您最初的问题,但也许从评论中回答您的问题将有助于解释事情。

The following code is an example of how you might instantiate a table with some methods.以下代码是如何使用某些方法实例化表的示例。

local function makeArray()
  local a = {}
  setmetatable(a, {__index = table})
  return a
end

The setmetatable call basically makes all the functions from the table library accessible from the new array. setmetatable调用基本上使table库中的所有函数都可以从新数组中访问。 This is useful, because all the table functions except pack expect an array as their first argument.这很有用,因为除了pack之外的所有table函数都需要一个数组作为它们的第一个参数。

Vanilla Lua does something similar for strings. Vanilla Lua 对字符串做了类似的事情。 All strings have {__index = string} as their metatable.所有字符串都有{__index = string}作为它们的元表。

luther is spot on although the code can be shortened:尽管代码可以缩短,但 luther 是正确的:

function makeArray()
  return setmetatable({}, {__index = table})
end

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM