繁体   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:

以下代码:

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

table.concat(tb)

可以这样写:

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

tb:concat()

我试图创建一个可以做同样事情的方法:

local tst = {}

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

但以下代码不起作用:

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

tb:test()

只有当我通知代码tb = tst时:

local tb = tst

tb:test()

我的问题是,我有什么方法可以像第二个示例那样自动创建与字符串或表一起使用的方法,而无需实例化 class? 比如,把我的表称为表:MyMethod()

我不确定这是否回答了您最初的问题,但也许从评论中回答您的问题将有助于解释事情。

以下代码是如何使用某些方法实例化表的示例。

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

setmetatable调用基本上使table库中的所有函数都可以从新数组中访问。 这很有用,因为除了pack之外的所有table函数都需要一个数组作为它们的第一个参数。

Vanilla Lua 对字符串做了类似的事情。 所有字符串都有{__index = string}作为它们的元表。

尽管代码可以缩短,但 luther 是正确的:

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

暂无
暂无

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

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